gpt4 book ai didi

canvas - 缩放后保持图像居中

转载 作者:行者123 更新时间:2023-12-05 00:49:57 56 4
gpt4 key购买 nike

我在 Canvas 上绘制了一张图像,我希望能够以任意比例放大和缩小,同时将图像保持在中心。为此,我的做法是改变 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 );
}

问题是如何计算 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;

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

最佳答案

为了中心。

最好这样做。 ctx 是 Canvas 上下文

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

或者根据需要,缩放 Canvas 并将原点保持在左上角。因为 Canvas 不会改变它的实际大小,所以你必须反转比例变化,这只是将它的大小除以比例而不是相乘。

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

关于canvas - 缩放后保持图像居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33311856/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com