【问题标题】:Keep the image centred after scaling缩放后保持图像居中
【发布时间】:2020-04-26 13:58:22
【问题描述】:

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

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;

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

【问题讨论】:

    标签: canvas html5-canvas


    【解决方案1】:

    为了中心。

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

    【讨论】:

    • 非常感谢,完美的答案。
    • 最后一个对我有用,因为我没有更改原始画布大小并使用 ctx.scale 进行缩放
    • 哇,一些坐标几何正在发生
    【解决方案2】:
      getWidth() {
            return this.rect.width * this.scale;
        }
    
        getHeight() {
            return this.rect.height * this.scale;
        }
    
        setScale(scale) {
    
            const oldWidth = this.getWidth();
            const oldHeight = this.getHeight();
            this.scale = scale;
            const newWidth = this.getWidth();
            const newHeight = this.getHeight();
    
            const addedWidth = newWidth - oldWidth;
            const addedHeight = newHeight - oldHeight;
    
            this.rect.pos.x -= addedWidth / 2;
            this.rect.pos.y -= addedHeight / 2;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2019-10-14
      • 2016-03-30
      相关资源
      最近更新 更多