HTML5画布缩放位置

HTML5 Canvas Scale position

本文关键字:缩放 位置 布缩放 HTML5      更新时间:2023-09-26

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

缩放画布(一半)后,我想设置当前位置。缩放总是将画布设置为pos 0,0(左上角)。

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


例子https://i.stack.imgur.com/SLG4v.png原创。
https://i.stack.imgur.com/8gHno.png需要的结果

你可以使用这个例子:

    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");
    const canvasArea = canvas.width * 2 + canvas.height * 2;
    const radius = canvasArea * 0.1;
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const color = 'blue';
    function drawCircle(context, scale, centerX, centerY, radius, color){
          context.save()
          context.beginPath();
          context.translate(centerX, centerY);
        context.scale(scale,scale);
          context.translate(-centerX,-centerY);
          context.arc(centerX, centerY, radius, 0, 2 * Math.PI);
        context.fillStyle = color;
        context.fill();    
        context.restore()
    }
    function change(el) {
      canvas.width = canvas.width;
      canvas.height = canvas.height;
        const scale = el.value / el.max;
        drawCircle(ctx, scale, centerX, centerY, radius, color);
    }
    change(document.getElementById('rangeInput'));
    <canvas id="myCanvas" width="200" height="200" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML canvas tag.</canvas>
    <br>
    
    <input id='rangeInput' type="range" min="0" max="100" value="100" oninput='change(this)' onchange='change(this)' style="width:200px">

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

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

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

你可以使用这个精确缩放,它在自定义的中心缩放点缩放你的图片(与数码相机lcd显示缩放的方式相同)并绘制它。

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