中心缩小画布

时间:2014-07-03 03:46:26

标签: javascript canvas

我正在增加图像的缩小效果。但是在缩放和缩小之后,图像不在画布的中心。

这是我的代码:

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);
}

提前致谢。

不过,这是它的小提琴:http://jsfiddle.net/huynq/RK2D7/

1 个答案:

答案 0 :(得分:1)

转换到您想要居中图像的位置。

演示: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();