【问题标题】:Javascript - rotating canvas causes stretching [duplicate]Javascript - 旋转画布导致拉伸[重复]
【发布时间】:2022-01-04 22:24:13
【问题描述】:

由于某种原因,如果您将画布纵横比设置为 2:1,则一切正常;任何其他纵横比都会使其拉伸。

const canvas = document.getElementById('canvas');

canvas.style.width = '400px';
canvas.style.height = '400px';
canvas.style.border = '2px solid black';

const ctx = canvas.getContext('2d');
const w = canvas.width/4;
const h = canvas.height/4;
var relativeAngle = 0;
//(Target is the position I want it; in this case, right in the middle)
const targetX = canvas.width/2;
const targetY = canvas.height/2;
const targetDist = Math.sqrt(targetX ** 2 + targetY ** 2);
const targetAngle = Math.atan(targetY / targetX) * 180 / Math.PI;
ctx.fillStyle = 'red'

function draw(){
    relativeAngle += 3;
    let targetRelativeAngle = targetAngle - relativeAngle;
    let targetRelativeX = targetDist * Math.cos(targetRelativeAngle * Math.PI / 180);
    let targetRelativeY = targetDist * Math.sin(targetRelativeAngle * Math.PI / 180);
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    
    ctx.rotate(relativeAngle * Math.PI / 180);
    ctx.translate(targetRelativeX,targetRelativeY);
    ctx.fillRect(-w/2,-h/2,w,h);
  
    ctx.restore();
  window.requestAnimationFrame(draw);
}
draw();

这里有什么问题和/或更好的方法是什么?

https://jsfiddle.net/1gx7bv3m/

【问题讨论】:

    标签: javascript css canvas


    【解决方案1】:

    我的经验不是将样式与画布混合...

    我们可以像这样直接在画布上设置纵横比:

    const canvas = document.getElementById('canvas');
    canvas.width = canvas.height = 400
    
    const ctx = canvas.getContext('2d');
    const w = canvas.width / 4;
    const h = canvas.height / 4;
    ctx.fillStyle = 'red'
    
    function refresh() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.translate(w, h)
      ctx.rotate(0.02);
      ctx.fillRect(-w / 2, -h / 2, w, h);
      ctx.translate(-w, -h)
      window.requestAnimationFrame(refresh);
    }
    refresh();
    <canvas id="canvas"></canvas>

    您可以看到,我还删除了您的许多计算,我希望我能完成您正在寻找的相同结果,代码更少,可读性更高。

    【讨论】:

    • “我希望我能完成您正在寻找的相同结果”您只是运气好,因为他们使用了一个足够小的矩形,该矩形被您的 clearRect 实际绘制的圆圈清除。只需将 wh 更改为画布的大小,您就会看到您的代码实际上是如何被破坏的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多