How can I change out an image using CamanJS? - javascript

I've got multiple images, and I'd like to load them each into a single <canvas> element at different points in time and then manipulate them using CamanJS. I can get the first image to appear like this:
Caman('#canvas-element', '/images/one.jpg');
But then when I subsequently try to update that same element using the following code, it does not work.
Caman('#canvas-element', '/images/two.jpg');
Is there some way to reset/clear/flush the canvas and load new image data into it, or do I really need to create separate <canvas> elements for each image I want to load? I'd prefer a single element because I don't want to eat up all the memory.

Remove the Caman attribute (data-caman-id) from the IMG or CANVAS element, change the image, and then re-render Caman.
document
.querySelector('#view_image')
.removeAttribute('data-caman-id');
const switch_img = '/to/dir/img.png';
Caman("#view_image", switch_img, function() {
this.render();
});

Hope followed code can help others who have same require.
function loadImage(source) {
var canvas = document.getElementById('image_id');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function() {
context.drawImage(image, 0, 0, 960, 600);
};
image.src = source;
}
function change_image(source) {
loadImage(source);
Caman('#image_id', source, function () {
this.reloadCanvasData();
this.exposure(-10);
this.brightness(5);
this.render();
});
}

Just figured this one out with a lot of trial and error and then a duh moment!
Instead of creating my canvas directly in my html, I created a container and then just did the following:
var retStr = "<canvas id=\"" + myName + "Canvas\"></canvas>";
document.getElementById('photoFilterCanvasContainer').innerHTML = retStr;
Caman("#" + myName + "Canvas", myUrl, function() {
this.render();
});
You want the canvas id to be unique each time you access the Caman function with a new image.

Related

Turning HTML content in to a canvas element [duplicate]

It would be incredibly useful to be able to temporarily convert a regular element into a canvas. For example, say I have a styled div that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement into the canvas, hide the original element and animate the canvas.
Can it be done?
There is a library that try to do what you say.
See this examples and get the code
http://hertzen.com/experiments/jsfeedback/
http://html2canvas.hertzen.com/
Reads the DOM, from the html and render it to a canvas, fail on some, but in general works.
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Its key trick was:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like ' +
'<span style="color:white; text-shadow:0 0 2px blue;">' +
'cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
That is, it used a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details — basically it's a lot more limited than an iframe or AJAX due to privacy and cross-domain concerns.)
Sorry, the browser won't render HTML into a canvas.
It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.
To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage and fillText, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle and relative positions of parts of it using offsetTop et al.)
You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:
var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(img, 0, 0);
parent.removeChild(node);
parent.appendChild(canvas);
};
img.src = pngDataUrl;
});
And here is jsfiddle
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
No such thing, sorry.
Though the spec states:
A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.
Which may be as close as you'll get.
A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.
The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.
You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.
this code work with the library: https://github.com/tsayen/dom-to-image
*the "id_div" is the id of the element html that you want to transform.
**the "canvas_out" is the id of the div that will contain the canvas
so try this code.
:
function Guardardiv(id_div){
var mode = 2 // default 1 (save to image), mode 2 = save to canvas
console.log("Process start");
var node = document.getElementById(id_div);
// get the div that will contain the canvas
var canvas_out = document.getElementById('canvas_out');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
};
if (mode == 1){ // save to image
downloadURI(pngDataUrl, "salida.png");
}else if (mode == 2){ // save to canvas
img.src = pngDataUrl;
canvas_out.appendChild(img);
}
console.log("Process finish");
});
}
so, if you want to save to image just add this function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
}
Example of use:
<html>
<head>
</script src="/dom-to-image.js"></script>
</head>
<body>
<div id="container">
All content that want to transform
</div>
<button onclick="Guardardiv('container');">Convert<button>
<!-- if use mode 2 -->
<div id="canvas_out"></div>
</html>
Comment if that work.
Comenten si les sirvio :)
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
function convert() {
dom = document.getElementById('divname');
var script,
$this = this,
options = this.options,
runH2c = function(){
try {
var canvas = window.html2canvas([ document.getElementById('divname') ], {
onrendered: function( canvas ) {
window.open(canvas.toDataURL());
}
});
} catch( e ) {
$this.h2cDone = true;
log("Error in html2canvas: " + e.message);
}
};
if ( window.html2canvas === undefined && script === undefined ) {
} else {.
// html2canvas already loaded, just run it then
runH2c();
}
}

replacing an image in canvs - javascript

I'm attempting to make a very simple meme generator, whereby you select the image you want to add text onto using a drop down menu. I can successfully select the image I want and display it within the canvas, however when I change my selection, instead of changing the image it adds it over the first image.
I'd like to be able to chose the image, and if i change my mind it simply replaces the current image. Any suggestions you might have would be very welcome!
Here's my code:
window.onload = function init(){
var selector = document.getElementById('selector');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imagesObj = {
"fry" : ['images/fry.jpg'],
"badluck" : ['images/badluck.jpg'],
"success" : ['images/success.jpg']
};
selector.addEventListener('change', function(){
imagesObj[selector.value].forEach(function(item){
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
};
imageObj.src = item;
});
});
}
It looks like this did the trick:
context.clearRect(0, 0, 298, 350);

Resize HTML canvas after loading image

See http://jsfiddle.net/jdb1991/6sxke/
I've got a canvas element that doesn't know what it's going to be used for until an image has loaded, so I need to be able to change the dimensions of the element on the fly, after creating the image object.
Something is going wrong though, as it seems to be running the commands asynchronously; writing the image to the context before the resize occurs.
use:
function objectifyImage(i) {
var img_obj = new Image();
img_obj.src = i;
return img_obj;
}
var canvas = document.getElementById('display');
var context = canvas.getContext('2d');
i = objectifyImage('https://www.google.co.uk/images/srpr/logo3w.png');
i.onload = function() {
canvas.width = i.width;
canvas.height = i.height;
context.drawImage(i, 0, 0);
};
​
demo: http://jsfiddle.net/ycjCe/1/
The element can be sized arbitrarily by CSS, but during rendering the
image is scaled to fit its layout size. (If your renderings seem
distorted, try specifying your width and height attributes explicitly
in the attributes, and not with CSS.)
source: https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Basic_usage
It appears i = objectifyImage will set the image src before the image.onload handler is defined. This will cause cached images to get loaded on some browsers prior to the onload definition. Its a good idea to always define onload handlers before setting the image.src to avoid timing issues with cached images.
var self = this;
.....
this.img = document.createElement('img');
this.img.onload = function () {
self.loaded = IMGSTATE_OK;
$Debug.log('loaded image:"' + self.img.src);
}
this.img.onerror = function () {
self.loaded = IMGSTATE_ERR;
$Debug.log('error image:"' + self.img.src);
}
this.img.src = href;
..... later on check the load state

Set an Image object as a div background image using javascript

I want to load 4 images from background showing a load bar to the client
and when the images will be downloaded i want to set them as background images to 4 div blocks.
I am looking for something like this.
var myImages = new Array();
for(var i = 0; i < 4; i++)
myImages[i] = new Image();
//load images using the src attribute
//and execute an on load event function where to do something like this.
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = myImage[index];
Is there any way to set a background image using an Image javascript object?
You can do something close to what you had. You don't set an image background to be an image object, but you can get the .src attribute from the image object and apply that to the backgroundImage. Once the image object has successfully loaded, the image will be cached by the browser so when you set the .src on any other object, the image will load quickly. You could use this type of code:
var imgSrcs = [...]; // array of URLs
var myImages = [], img;
for (var i = 0; i < 4; i++) {
img = new Image();
img.onload = function() {
// decide which object on the page to load this image into
// this part of the code is missing because you haven't explained how you
// want it to work
var div0 = document.getElementById('theDivId');
div0.style.backgroundImage = "url(" + this.src + ")";
};
img.src = imgSrcs[i];
myImages[i] = img;
}
The missing part of this code is deciding which objects on the page to load which image into when the image loads successfully as your example stood, you were just loading each one into the same page object as soon as they all loaded which probably isn't what you want. As I don't really know what you wanted and you didn't specify, I can't fill in that part of the code.
One thing to watch out for when using the .onload event with images is you have to set your .onload handler before you set the .src attribute. If you don't, you may miss the .onload event if the image is already cached (and thus it loads immediately).
This way, the image shows up instantly all in one once it's loaded rather than line by line.
function setBackgroundImage(){
imageIsLoaded(myURL).then(function(value) {
doc.querySelector("body > main").style.backgroundImage = "url(" + myURL + ")";
}
}
function imageIsLoaded(url){
return new Promise(function(resolve, reject){
var img = new Image();
try {
img.addEventListener('load', function() {
resolve (true);
}, false);
img.addEventListener('error', function() {
resolve (false);
}, false);
}
catch(error) {
resolve (false);
}
img.src = url;
});
}

Loop through images with shared class in Jquery and apply Pixastic filter

I am using pixastic (http://www.pixastic.com/lib/docs/actions/blend/) on a site I am implementing and need to use JQuery to loop though a collection of images that have a shared class and apply blend code to each image.
The sample code on the pixastic site doesn't make much sense to me (it looks like it is creating a new image) any help would be really appreciated.
var img = new Image();
img.onload = function() {
var blendImg = new Image();
blendImg.onload = function() {
Pixastic.process(img, "blend",
{
amount : 1,
mode : "multiply",
image : blendImg
}
);
}
blendImg.src = "blendimage.jpg";
}
img.src = "myimage.jpg";
Kind of a shot in the dark here, but does this work?
$("img.yourClass").each(function() {
Pixastic.process($(this).get(0), "blend", {
amount: 1,
mode: "multiply",
image: [imageToBlendItWith]
});
});

Categories