缩放后保持图像居中

Sop*_*rus 1 canvas html5-canvas

我有一个在画布上绘制的图像,我希望能够以任意比例放大和缩小,同时将图像保持在中心。为此,我的方法是更改​​画布上下文的比例并重新绘制图像,但是我需要计算新图像的左上角,否则它将不会居中。

function zoom( canvas, context, scale ) {
    var image = new Image();
    image.src = canvas.toDataURL( 'image/png' );
    canvas.clearRect( 0, 0, canvas.width, canvas.height );
    context.scale( scale, scale );
    var x = ???,
        y = ???;
    context.drawImage( image, x, y );
}
Run Code Online (Sandbox Code Playgroud)

问题是如何计算x以及y以何种方式适用于任何规模。我已经找出了一些特殊情况,但是找不到一般规则。当比例为0.5时,保持图像居中的规则是:

var x = canvas.width / 2,
    y = canvas.height / 2;
Run Code Online (Sandbox Code Playgroud)

小数位数为2时,规则为:

var x = -canvas.width / 4,
    y = -canvas.height / 4;
Run Code Online (Sandbox Code Playgroud)

当比例为3时,规则为:

var x = -canvas.width / 3,
    y = -canvas.height / 3;
Run Code Online (Sandbox Code Playgroud)

那么一般规则是什么?还是有更好的方法?

Bli*_*n67 5

为中心。

最好这样做。ctx是画布上下文

// scale the coordinate system to required scale and set the origin (0,0) 
// to the center of the canvas
ctx.setTransform(scale, 0, 0, scale, ctx.canvas.width / 2, ctx.canvas.height / 2);
ctx.drawImage(image,-image.width / 2,-image.height / 2); // draw the image offset by half
Run Code Online (Sandbox Code Playgroud)

或者您可以避免设置转换,而只需按比例绘制图像

// get the position is half of the canvas width minus the scaled width of the image 
var x = (ctx.canvas.width - image.width * scale) / 2;
var y = (ctx.canvas.height - image.height * scale) / 2;
ctx.drawImage(image, x, y, image.width * scale, image.height * scale); // drw image with scaled width and height 
Run Code Online (Sandbox Code Playgroud)

或者,根据需要缩放画布并将原点保留在左上角。由于画布不会更改其实际大小,因此您必须反转比例更改,这仅意味着将其大小除以比例而不是相乘。

ctx.scale(scale, scale);
var x = (ctx.canvas.width / scale - image.width) / 2;
var y = (ctx.canvas.height / scale - image.height) / 2;
ctx.drawImage(image, x, y);
Run Code Online (Sandbox Code Playgroud)