Canvas+SVG路径中的Atan2旋转断断续续

Atan2 rotational stutter in Canvas + SVG path

本文关键字:旋转 断断续续 Atan2 路径 Canvas+SVG      更新时间:2023-09-26

以前我用svg构建了一个运动路径,但注意到在移动设备上的渲染性能不太好。我决定将运动路径转换为canvas,这将给我更好的性能。

我选择用svg创建我的canvas路径的克隆,这样我就可以使用getPointAtLength()getTotalLength()方法来获得相应的采样点的xy值以及canvas路径的长度

问题是,用getPointAtLength采样后返回的值似乎会导致不规则的旋转。

我有一种预感,这与我使用getPointAtLength()方法沿着路径采样的位置差异有关。

如何固定从atan2返回的值,使其沿路径平滑线性旋转?

var canvas = document.body.querySelector('.loader__canvas');
var source = document.body.querySelector('.loader__source');
var ctx = canvas.getContext("2d");
var angle;
var speed = 0.5;
var deltaX;
var deltaY;
var nextCoords;
var prevCoords;
var offset = 0;
var distance = source.getTotalLength();
render();
function render() {
  // Reset the loop once offset exceeds the path's distance
  if (offset >= distance) {
    offset = 1 * speed;
  } else {
    offset += 1 * speed;
  }
  // Clear the canvas from all previous operations
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw the loop that the object is attached to
  ctx.beginPath();
  ctx.lineWidth = 10;
  ctx.moveTo(250, 250);
  ctx.lineTo(250, 300);
  ctx.arc(300, 300, 50, Math.PI, -Math.PI / 2, true);
  ctx.lineTo(200, 250);
  ctx.arc(200, 200, 50, Math.PI / 2, 0);
  ctx.lineTo(250, 250);
  ctx.strokeStyle = '#ddd';
  ctx.stroke();
  ctx.closePath();
  // Save the current transformation matrix for future reset
  ctx.save();
  // Calculate coordinates and angle for the object,
  // if prevCoords is undefined: assign initial values
  prevCoords = nextCoords || source.getPointAtLength(offset);
  nextCoords = source.getPointAtLength(offset);
  angle = Math.atan2(
    (nextCoords.y - prevCoords.y), (nextCoords.x - prevCoords.x)
  ) + (Math.PI / 2);
  // Apply transforms
  ctx.translate(nextCoords.x, nextCoords.y);
  ctx.rotate(angle);
  // Draw path object
  ctx.beginPath();
  ctx.arc(0, 0, 20, 0, Math.PI);
  ctx.fillStyle = '#f63';
  ctx.fill();
  ctx.closePath();
  // Restore transforms
  ctx.restore();
  // Loop
  requestAnimationFrame(render);
}
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.loader__canvas {
  display: block;
  width: 100%;
  max-width: 500px;
  max-height: 500px;
  margin: auto;
  border: 1px solid #ccc;
}
.loader__source {
  fill: transparent;
  stroke: #ddd;
  stroke-width: 10;
}
<canvas class="loader__canvas" width="500" height="500">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
    <path class="loader__source" d="m250,250v50a50,50,0,1,0,50,-50h-100a50,50,0,1,1,50,-50z" />
  </svg>
</canvas>

更新的示例

在Blindman67答案的帮助和建议下,我结合prevCoords上的%运算符增加了偏移量。Math.atan2()现在似乎工作得很好,并且沿着路径的旋转是平滑的。

然而,我想知道为什么偏移量为1会引起如此大的振荡,而偏移量为10则不会?

var canvas = document.body.querySelector('.loader__canvas');
var source = document.body.querySelector('.loader__source');
var ctx = canvas.getContext("2d");
var angle;
var speed = 5;
var deltaX;
var deltaY;
var offset = 0;
var nextCoordsPlug;
var prevCoordsPlug;
var nextCoordsSocket;
var prevCoordsSocket;
var distance = source.getTotalLength();
render();
function render() {
  // Reset the loop once offset exceeds the path's distance
  if (offset >= distance) {
    offset = 1 * speed;
  } else {
    offset += 1 * speed;
  }
  // Clear the canvas from all previous operations
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.setLineDash([source.getTotalLength() - 50, 50]);
  ctx.lineDashOffset = -(offset + 40);
  // Draw the loop that the object is attached to
  ctx.beginPath();
  ctx.lineWidth = 20;
  ctx.moveTo(250, 250);
  ctx.lineTo(250, 300);
  ctx.arc(300, 300, 50, Math.PI, -Math.PI / 2, true);
  ctx.lineTo(200, 250);
  ctx.arc(200, 200, 50, Math.PI / 2, 0);
  ctx.lineTo(250, 250);
  ctx.strokeStyle = '#f63';
  ctx.stroke();
  ctx.closePath();
  // Save the current transformation matrix for future reset
  ctx.save();
  // Calculate coordinates and angle for the object,
  // use the remainder to extend the point past the distance
  prevCoordsPlug = source.getPointAtLength((offset + 10) % distance);
  nextCoordsPlug = source.getPointAtLength(offset);
  angle = Math.atan2(
    (nextCoordsPlug.y - prevCoordsPlug.y), (nextCoordsPlug.x - prevCoordsPlug.x)
  ) - (Math.PI / 2);
  // Apply transforms
  ctx.translate(nextCoordsPlug.x, nextCoordsPlug.y);
  ctx.rotate(angle);
  // Draw path object
  ctx.beginPath();
  ctx.arc(0, 0, 20, 0, Math.PI);
  ctx.rect(-12, -20, 8, 20);
  ctx.rect(4, -20, 8, 20);
  ctx.fillStyle = '#f63';
  ctx.fill();
  ctx.closePath();
  // Restore and save previous transforms
  ctx.restore();
  ctx.save();
  prevCoordsSocket = source.getPointAtLength((offset + 45) % distance);
  nextCoordsSocket = source.getPointAtLength((offset + 35) % distance);
  angle = Math.atan2(
    (nextCoordsSocket.y - prevCoordsSocket.y), (nextCoordsSocket.x - prevCoordsSocket.x)
  ) + (Math.PI / 2);
  // Apply transforms
  ctx.translate(nextCoordsSocket.x, nextCoordsSocket.y);
  ctx.rotate(angle);
  // Draw path object
  ctx.beginPath();
  ctx.arc(0, 0, 20, 0, Math.PI);
  ctx.fillStyle = '#f63';
  ctx.fill();
  ctx.closePath();
  // Restore transforms
  ctx.restore();
  // Loop
  requestAnimationFrame(render);
}
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.loader__canvas {
  display: block;
  width: 100%;
  max-width: 500px;
  max-height: 500px;
  margin: auto;
  transform: rotate(-45deg) translateZ(0);
}
.loader__source {
  fill: transparent;
  stroke: #ddd;
  stroke-width: 10;
}
<canvas class="loader__canvas" width="500" height="500">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
    <path class="loader__source" d="m250,250v50a50,50,0,1,0,50,-50h-100a50,50,0,1,1,50,-50z" />
  </svg>
</canvas>

像素位置

我不确定为什么会发生这种情况,尽管我使用了一些有缺陷的逻辑,意外地找到了解决方案。为了对抗这种情况,请在离偏移稍远的地方找到点。我添加了4个像素,得到了之前的位置prevCoords = source.getPointAtLength((offset + 4) % distance);,我向前看,以确保负偏移不会打乱开始。

即使移动偏移,方向仍然有点粗糙。所以我在角度上添加了一个简单的平滑算法。保持单独的值angleReal以显示平滑的角度,并保持angleDelta以平滑运动。有一个CCD_ 16和CCD_。不同的值将影响平滑。如果drag的值超过0.5,平滑将开始振荡(有时效果很好,但在这种情况下不需要)

还有一个问题是,atan2将角度-Math.PI返回到Math.PI。平滑将-Math.PIMath.PI视为两个不同的角度,但它们是相同的,所以我添加了一个测试,以确保从-Math.PIMath.PI的转换不会使平滑旋转对象。

下面是你的代码,我修改了一些位来平滑对象方向。这不是唯一的解决方案,但它是我将用于动画的解决方案。

更新

在进一步的调查中,我发现函数getPointAtLength有故障。

使用以下代码(在您的代码上下文中),我将getTotalLength给出的距离与使用getPointAtLength 对路径进行采样所覆盖的距离进行比较

  var distance = source.getTotalLength(); // get the distance along the path;
  var next;         // next point 
  var dist = 0;     // the measured distance
  var step = 1;     // path sample rate
  var last = source.getPointAtLength(0);      // get the first point
  for(var i = step; i < distance; i+= step){  // sample points 
      next = source.getPointAtLength(i);      // get a point at offset i
      // get and sum the distance between the two samples 
      dist += Math.sqrt(Math.pow(next.x-last.x,2)+Math.pow(next.y-last.y,2));
      last = next;   // move the current sample to the last
  }
  // sample the last remaining bit 
  next = source.getPointAtLength(distance);
  // add that distance.
  dist += Math.sqrt(Math.pow(next.x-last.x,2)+Math.pow(next.y-last.y,2));
  // show result
  console.log("Measured:"+dist.toFixed(2)+" Given:"+distance.toFixed(2))

在1、0.1和0.01 下的采样结果

  • 674.64用于1的样本步骤
  • 833.49,样本步长为0.1
  • 944.37,样本步长为0.01

source.getTotalLength()给出的距离为671.31。

人们预计误差会随着采样距离的减少而减少,但它会增加,强烈指向函数"getPointAtLength"中的错误,并解释计算方向时的不准确之处。函数getPointAtLength没有返回精确地在路径上的点。

var canvas = document.body.querySelector('.loader__canvas');
var source = document.body.querySelector('.loader__source');
var ctx = canvas.getContext("2d");
var angle;
// Blindman67 change start---------------------------------
var angleReal;
var angleDelta;
var drag = 0.1;
var acceleration = 0.9;
// Blindman67 change end---------------------------------
var speed = 0.5;
var deltaX;
var deltaY;
var nextCoords;
var prevCoords;
var offset = 0;
var distance = source.getTotalLength();
render();
function render() {
  // Reset the loop once offset exceeds the path's distance
  if (offset >= distance) {
    offset = 1 * speed;
  } else {
    offset += 1 * speed;
  }
  // Clear the canvas from all previous operations
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // Draw the loop that the object is attached to
  ctx.beginPath();
  ctx.lineWidth = 10;
  ctx.moveTo(250, 250);
  ctx.lineTo(250, 300);
  ctx.arc(300, 300, 50, Math.PI, -Math.PI / 2, true);
  ctx.lineTo(200, 250);
  ctx.arc(200, 200, 50, Math.PI / 2, 0);
  ctx.lineTo(250, 250);
  ctx.strokeStyle = '#ddd';
  ctx.stroke();
  ctx.closePath();
  // Save the current transformation matrix for future reset
  ctx.save();
  // Calculate coordinates and angle for the object,
  // if prevCoords is undefined: assign initial values
  // Blindman67 change start---------------------------------
  // get the offset a larger pixel distance
  prevCoords = source.getPointAtLength((offset+4)%distance);
  // Blindman67 change end ---------------------------------
  nextCoords = source.getPointAtLength(offset);
  angle = Math.atan2(
    (nextCoords.y - prevCoords.y), (nextCoords.x - prevCoords.x)
  ) + (Math.PI / 2);
  // Blindman67 change start---------------------------------
  if(angleDelta === undefined){  // if not set set up init vals
     angleDelta = 0;
     angleReal = angle;
  }
  if(Math.abs(angle-angleReal) > Math.PI){
     angleReal = angle;
  }
  // add smoothing to the angle
  angleDelta += (angle-angleReal)*acceleration;
  angleDelta *= drag;
  angleReal += angleDelta;
  // Apply transforms
  ctx.translate(nextCoords.x, nextCoords.y);
  ctx.rotate(angleReal+Math.PI);
  // Blindman67 change end ---------------------------------
  // Draw path object
  ctx.beginPath();
  ctx.arc(0, 0, 20, 0, Math.PI);
  ctx.fillStyle = '#f63';
  ctx.fill();
  ctx.closePath();
  // Restore transforms
  ctx.restore();
  // Loop
  requestAnimationFrame(render);
}
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.loader__canvas {
  display: block;
  width: 100%;
  max-width: 500px;
  max-height: 500px;
  margin: auto;
  border: 1px solid #ccc;
}
.loader__source {
  fill: transparent;
  stroke: #ddd;
  stroke-width: 10;
}
<canvas class="loader__canvas" width="500" height="500">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500">
    <path class="loader__source" d="m250,250v50a50,50,0,1,0,50,-50h-100a50,50,0,1,1,50,-50z" />
  </svg>
</canvas>