HTML5 Canvas Scale位置

时间:2015-09-26 04:18:08

标签: javascript html5 canvas

我第一次尝试画布并且有一些关于缩放的问题。

我将画布向上缩放(一半)后,我想设置当前位置。比例始终将画布设置为pos 0,0(左上角)。

如果有人知道如何在缩放时改变位置,请留下答案!

实施例
原文http://i.stack.imgur.com/SLG4v.png http://i.imgur.com/2nmJZJH.png需要结果。

2 个答案:

答案 0 :(得分:0)

获取您在图像中显示的内容。

// ctx is the canvas 2d context
// img is the image
function showImageScaled(img,scale,x,y){
    // scale is how big you want it. 
    // x and y are where in the image you want the top left to be
    ctx.setTransform(scale,0,0,scale,0,0);
    ctx.drawImage(img,-x,-y); // move the image
}

所以要查看缩小到两倍的顶角

showImageScaled(img,2,0,0);

显示左上角的中心,图像缩放4次

showImageScaled(img,4,img.width/2,img.height/2);

希望这有帮助。

答案 1 :(得分:0)

Blindman67

给出的解决方案的替代方案

您可以使用此精确缩放,在自定义中央缩放点(与数码相机液晶显示器缩放的方式相同)缩放图片并绘制它。

function precisionScale(img,scale,x,y){
        /** Function precisionScale
         * The function scales the image with a custom central scaling point
         * as opposed to 0,0 (top,left) default central scaling point
         */
        ctx.translate(x,y);
        ctx.scale(scale,scale);
        ctx.drawImage(img,-x,-y);
        ctx.scale(-scale,-scale);
        ctx.translate(-x,-y);
    }