javascript - Canvas + SVG 路径中的 Atan2 旋转卡顿

标签 javascript math canvas svg

之前我使用 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's answer的帮助和建议下,我结合 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); 我向前看以确保负偏移不会搞乱开始。

即使移动偏移量,方向仍然有点粗糙。所以我为 Angular 添加了一个简单的平滑算法。保留一个单独的值 angleReal 以显示平滑的 Angular 和一个 angleDelta 以平滑运动。有一个 dragacceleration 组件决定了行为。不同的值会影响平滑。如果 drag 的值超过 0.5,平滑将开始振荡(有时效果不错,但在这种情况下不需要)

还有一个问题是 atan2 返回 Angular -Math.PIMath.PI 平滑看到 -Math .PIMath.PI 作为两个不同的 Angular ,但它们是相同的所以我添加了一个测试以确保从 -Math.PI 的过渡Math.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>

关于javascript - Canvas + SVG 路径中的 Atan2 旋转卡顿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34233288/

相关文章:

math - 六边形网格坐标到像素坐标

javascript - 旋转后得到正确的左上角坐标

javascript - Fabric.js "reverse"和 "layered"剪裁/剪裁

javascript - jquery 图像 slider "Unslider"无法正常工作

c# - 服务器级 SDK 可以加载 PDF 文件并执行计算和验证代码片段?

java - 1到30之间不能被3整除的数

JavaScript - 删除线框时三 Angular 形之间的间隙

javascript - jQuery 标签 'for' 属性选择器

javascript - 如何使用 webpack 为输出文件添加前缀?

python - 如何在 Python 中使用 x^2 进行(空中飞人)集成?