Resize HTML canvas after loading image - javascript

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

Related

Multiple Images displaying last image with dynamically created canvas and assigning to images

function innerAjax(FILE_DIR,imgJPGList){
var imgLength = imgJPGList.length;
$("#imgID").empty();// This is a div
if(imgLength!=0){
img = [];
for(i=0;i< imgLength;i++){
// dir = FILE_DIR+"/"+imgJPGList[i];
var canvasCreator = document.createElement("canvas");
canvasCreator.id = imgJPGList[i].substr(0, imgJPGList[i].indexOf('.'));
console.log("canvas id is---"+canvasCreator.id);
var canvas = $(canvasCreator).get(0);
var ctx = canvas.getContext('2d');
img[i] = new Image();
img[i].onload = function() {
console.log("inside onload function");
ctx.drawImage(img[i],0,0);
}
img[i].src = FILE_DIR+"/"+imgJPGList[i];
canvas.width = img[i].width;
canvas.height = img[i].height;
$("#imgID").append(canvas);
$("#imgID").append($("<br/>"));
}
}
$(canvas).mouseover(function myDown(e)
{
console.log("mouseover-----");
})
}
I have multiple images in a single page i am trying to create a dynamic canvas and set image height and width to it so that i could do some annotation on images. But my last image is getting displayed every time or nothing is displayed. Anyhelp is appreciated.
You are doing an asynchronous operation inside a loop which rarely work as intended.
JavaScript is single-threaded which means the code inside the onload handler won't be called before the loop finish, hence i will always be the last image.
You should also move setting canvas size to inside the handler as images not fully loaded doesn't have a width/height (it works on your system only because the images are in the browser cache).
To fix the last image problem, use this inside the handler which will represent the image loaded at that point:
img[i] = new Image();
...
img[i].onload = function() {
// at the time this gets called, the loop has finished
// these need to be here as image won't have width/height until fully loaded
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0,0); // use this (= actual image loaded)
// append canvas to DOM here etc....
}
img[i].src = FILE_DIR+"/"+imgJPGList[i];

How can I change out an image using CamanJS?

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.

Display Image using canvas in JavaScript/jQuery

I have the following code :
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Image: <img src="'+pastedImage.src+'" height="700" width="700"/>');
}
pastedImage.src = source;
}
Here I am displaying the image through html image tag which I wrote in document.write and provide appropriate height and width to image.
My question is can it possible to displaying image into the canvas instead of html img tag? So that I can drag and crop that image as I want?
But how can I display it in canvas?
Further I want to implement save that image using PHP but for now let me know about previous issue.
Try This
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here This is essential as it waits till image is loaded before drawing it.
ctx.drawImage(img , 0, 0);
};
img.src = 'myImage.png'; // Set source path
Make sure the image is hosted in same domain as your site. Read this for Javascript Security Restrictions Same Origin Policy.
E.g. If your site is http://example.com/
then the Image should be hosted on http://example.com/../myImage.png
if you try http://facebook.com/..image/ or something then it will throw security error.
Use
CanvasRenderingContext2D.drawImage.
function createImage(source) {
var ctx = document.getElementById('canvas').getContext('2d');
var pastedImage = new Image();
pastedImage.onload = function(){
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage = source;
}
Also MDN seems to be have nice examples.

How to get the downloaded image's width&height?

I want to set the width and height of the container <div> of <img> after the image is downloaded, how to do it?
function fn (div, url_path) {
var img = new Image();
img.onload = function () {
div.style.width = img.width;
div.style.height = img.height;
};
img.src = "url_path";
}
fn(document.getElementsByTagName('div')[0], 'http://some-url-to-image.com/1.jpg');
Put it on the page hidden, then measure its width. See here for a good explanation of how to measure the width of a hidden object (just calling width() returns 0).
It is best to wait for the image to be loaded unless you want false results.
jQuery('#image').load(function() {
var jThis = jQuery(this);
var width = jThis.width();
var height = jThis.height();
yourFunction(width, height); //whatever you want to do with these values
jThis.unbind('load'); //might be necessary if you only want this to happen once. Remove this if #image is a container for multiple uses.
})
EDIT 1
Instead of yourFunction(), you could use this since it fits your description better:
jThis.parents('#container').css({
width: width,
height: height
});

swapping images of different sizes [Javascript vs IE]

I have the following simple preloading function which substitute an image "src" attribute with another image (an animated GIF "Loading"). The problem arises only in IE: if the "loading" GIF is smaller than the actual image src, that will be resized. For example if I have a square 100px image and preload it, the image is temporarly substituted by an animated GIF of 50x50px. Whem the original image is fully loaded it is NOT displayed at its size, but at the smaller 50px. Here is the code, if you need it
_preload = function(url, placeholderUrl) {
var img = new Image();
loading = true;
var placeholder = new Element("img", {
src: placeholderUrl
});
img.placeholder = placeholder;
img.onload = function(evt) {
this.placeholder.src = this.src;
loading = false;
}
img.src = url;
return placeholder;
}
Here you can see the visual error
You should be able to adjust the width/height of the image within the callback function:
img.onload = function(evt) {
this.placeholder.src = this.src;
this.placeholder.width = this.width;
this.placeholder.height = this.height;
loading = false;
}
Example: Resizing image onLoad
I guess replacing placeholder with img (the img-elements inside the dom), instead of simply changing the src-attribute of placeholder, should fix this issue.

Categories