Question

I'm having some issues using the drawImage method to place a pre-loaded image larger then 250PX width and height onto a canvas.

//Canvas

var canvas = document.createElement("canvas");
var contex = canvas_image.getContext('2d');
canvas.width = 350;
canvas.height = 350;
canvas.id = 'canvas'
$('.canvas').append(canvas);

//Draw Image to canvas

var imageObj = new Image();
imageObj.onload = new function() {
    contex.drawImage(imageObj, 0, 0);
};
imageObj.src = $('img').attr('src');

I can't seem to get it to work with an image larger then 250PX Width or Height. But under 250 the image shows... It's really odd and frustrating.

Was it helpful?

Solution

You must get the context from the canvas element. The code you are showing in the post (not sure if it's a typo that happen when posting the question or not? though you shouldn't be able to draw anything if it's not a typo :-) ) has the following error:

This line:

var contex = canvas_image.getContext('2d');

should be:

var contex = canvas.getContext('2d');

as canvas_image does not seem to exist.

If you already have an image loaded you can draw that directly onto canvas instead - there is no need to do a second load of the image:

contex.drawImage($('img')[0], 0, 0);

just make sure you tap into its load event first as you do with the off-screen image.

var img = $('img');

img.on('load', function(e) {
    contex.drawImage(img[0], 0, 0);
}

or call it on window's load event.

Other things to look out for is if the image actually has data in the 350x350 pixel area in top left corner (in case the image is very large). You can test by drawing it scaled to see if there is information there:

contex.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top