redGREENblue
redGREENblue

Reputation: 3126

Cropping scaled down images

I am not exactly sure how to describe the problem, so let me explain it with an example.

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

Answers (1)

Loktar
Loktar

Reputation: 35309

Live Demo

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

Related Questions