I’m using Canvas to perform a couple of things on an image which is loaded/drawn using image.onload & context.drawImage combo. I’m calculating the bounding size for scaling the images using a simple function which returns the values. I need those values for use at a later point in my code, but no matter what I do, I’m not able to assign the values to a variable. I’m also not able to access my Canvas’s styleheight/stylewidth attributes after I assign it the calculated dimensions.
Here’s a pseudos ample of my code
$(document).ready(function(){
//Canvas access, context reference etc here.
//Since I'm assigning styles to the canvas on the fly, the canvas has no ht/wdt yet
var dimes = '';
var image = new Image();
image.onload = function(){
//Apply original image height/width as canvas height/width 'attributes'
//(so that I can save the original sized image)
//Check if the image is larger than the parent container
//Calculate bounds if not
//Apply calculated dimensions as 'style' height/width to the canvas, so that the image fits
dimes = scaleImage(...);
//Works!
console.log(dimes);
//Rest all code
}
image.src = '...';
//Blank!!!
console.log(dimes);
//These all blank as well!!!
jQuery('#mycanvas').height() / width() / css('height') / css('width');
document.getElementById(canvas).style.height / .style.width / height / width;
});
I need to access the calculated dimensions for a ‘reset’ kind of function, that resets my canvas with the drawn image to the calculated size.
As @apsillers noted, the
console.log(dimes)code is being executed after you simply define theimage.onload()event handler.If you want to access
dimesoutside ofimage.onload(), you’ll need to ensure it’s being executed after the image loads… e.g. as a response to a button click.Put the
var dimes = "";before the$(document).ready()to make it a global variable.Then if you need to access
dimesin an event handler, it’s ready for you:Of course,
dimeswill now only be accessible inside this first$(document).ready()event handler. If you add another one (which you can certainly do in jQuery), you’ll need to use the$.fn.data()jQuery object method to storedimes: