I\'m working on some simple image manipulation functions with canvas. The user uploads an image, is able to rotate and crop it and then clicks ok. The image is then split in
The bug occurs when drawImage()
is called out of the bounds of the sourceImage.
You have to double check that the source width and source height are always smaller or equal to the image's width and height :
So for the first if block :
var sourceX = image.width/2;
var sourceY = 0;
var sourceWidth = image.width - sourceX; // you're in the bounds
var sourceHeight = image.height;
var destX = canvas.width/2;
var destY = 0;
var destWidth = canvas.width;
var destHeight = canvas.height;
ctx.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
Or as a one-liner :
ctx.drawImage(image, image.width/2, 0, image.width - (image.width/2), image.height, canvas.width/2, 0, canvas.width, canvas.height);