Reputation: 110
I'm iplementing zoom out effect of an image. But after it's scaled and zoom out, the image isn't on center of canvas.
This is my code:
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var ctx = canvas.getContext("2d");
var zoomDelta = 0.025; // 10 steps in 10s, scale from 5 to 1
var currentScale = 5;
var img = new Image();
img.src = image.src;
img.onload = function() {
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
}
$("#start").on("click", function () {
ctx.translate(canvas.width / 2, canvas.height / 2);
drawImage();
var zoom1 = window.setInterval(
function() {
if(currentScale < 1)
window.clearInterval(zoom1);
else
reDraw();
}, 50
);
});
function reDraw() {
currentScale -= zoomDelta;
drawImage();
}
function drawImage() {
clear();
ctx.save();
ctx.scale(currentScale, currentScale);
ctx.drawImage(img, -img.width / 2, -img.width / 2);
ctx.restore();
}
function clear() {
ctx.clearRect(-img.width / 2 - 2, -img.width / 2 - 2, img.width + 4, img.height + 4);
}
Thanks in advance.
Btw, this is its fiddle: http://jsfiddle.net/huynq/RK2D7/
Upvotes: 0
Views: 1468
Reputation: 105015
Translate to the point on which you want to center the image.
A Demo: http://jsfiddle.net/m1erickson/QEuw4/
var cx=canvas.width/2;
var cy=canvas.height/2;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(cx,cy);
ctx.scale(scale,scale);
ctx.drawImage(img,-img.width/2,-img.height/2);
ctx.restore();
Upvotes: 1