2015-10-23 77 views
1

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

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

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

var x = canvas.width/2, 
    y = canvas.height/2; 

当比例尺为2,则该规则是:

var x = -canvas.width/4, 
    y = -canvas.height/4; 

而当比例为3时,该规则是:

var x = -canvas.width/3, 
    y = -canvas.height/3; 

那么通用规则是什么?还是有更好的方法?

回答

2

以中心为准。

最好这样做。 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 

或者,您可以设置避免转型,只是绘制图像缩放

// 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 

或者只要你想,缩放画布并保持起源于左上角。由于画布不会改变其实际尺寸,因此您必须反转比例尺变化,这意味着将尺寸除以比例而不是乘以。

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); 
+0

非常感谢,完美的答案。 – Sophivorus