Reputation: 3126
I am not exactly sure how to describe the problem, so let me explain it with an example.
Suppose I have a canvas setup with the width and height of 600x400.
Now, I can chose an image (which can be of any dimension but usually bigger than 600x400) and draw it on the canvas.
Now I need to crop the original image (suppose in this case it is 1000x500 px) to 400x200 px.
How do I go about this to make sure I am cropping the original sized image while displaying the scaled down image on the canvas?
I am preferably looking at a completely client side solution.
Upvotes: 0
Views: 127
Reputation: 35309
Its actually very easy. All you need to do is draw the image to a canvas of the size you want, and call toDataUrl()
on it afterwards to get the resulting image data. Drawing the image itself to a different canvas doesn't affect the output at all as long as you are drawing the contents of the original image to the cropped area.
var canvas = document.getElementsByTagName("canvas")[0],
context = canvas.getContext("2d"),
img = document.getElementsByTagName("img")[0];
canvas.width = 600;
canvas.height = 400;
context.drawImage(img, 0,0,600,400);
var croppedCanvas = document.getElementById("tempCanvas"),
croppedCtx = croppedCanvas.getContext("2d");
croppedCanvas.width = 400;
croppedCanvas.height = 200;
croppedCtx.drawImage(img, 0, 0);
Upvotes: 2