javascript - 以自身为中心旋转一个三 Angular 形

标签 javascript html5-canvas

我想在自身中心旋转一个三 Angular 形。 我有这个脚本:

  var ctx = canvas.getContext('2d');
  var angle = 30;
  setInterval(rotate, 50);
  function rotate() {
  ctx.fillStyle = "white";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.save();
    ctx.translate(150, 150); // x, y
    ctx.rotate(angle * Math.PI / 180)
    ctx.fillStyle = "yellow";
    var path=new Path2D();
    path.moveTo(-50+50,-25);
    path.lineTo(-50,-50-25);
    path.lineTo(-50-50,-25);
    ctx.fill(path);
    ctx.restore();
    angle++;
  }
<canvas id="canvas" width="1800" height="700"></canvas>

它旋转它,但不在中心。我希望它看起来像这样:

  var ctx = canvas.getContext('2d'); 
  setInterval(rotate, 50);
  var angle = 30;
  function rotate() {
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate(50, 50);
    ctx.rotate(angle * Math.PI / 180)

    ctx.fillStyle = "green";
    ctx.fillRect(-25, -25, 50, 50);
    ctx.restore();
    angle++;
    }
<canvas id="canvas" width="1800" height="700"></canvas>
我想,我只需要得到三 Angular 形的宽度和高度并将其除以 2,但我不知道该怎么做。 感谢每一个答案!

最佳答案

你想要的是centroid你的形状。

var ctx = canvas.getContext('2d');
var angle = 30;
var points = [
  {x:0, y:-25},
  {x:-50, y:-75},
  {x:-100, y:-25}
];
// first sum it all
var sums = points.reduce( (sum, point) => {
  sum.x += point.x;
  sum.y += point.y;
  return sum;
}, {x:0, y:0});
// we want the mean
var centroid = {
  x: sums.x / points.length,
  y: sums.y / points.length
};

rotate();
function rotate() {
  ctx.setTransform(1,0,0,1,0,0);
  ctx.fillStyle = "white";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  // general position in canvas
  ctx.translate(100, 100);
  // move to centroid of our triangle
  ctx.translate(centroid.x, centroid.y); // x, y
  // rotate
  ctx.rotate(angle * Math.PI / 180)
  // go back to our initial position
  ctx.translate(-centroid.x, -centroid.y); // x, y

  ctx.fillStyle = "yellow";
  var path=new Path2D();
  path.moveTo(points[0].x, points[0].y);
  path.lineTo(points[1].x, points[1].y);
  path.lineTo(points[2].x, points[2].y);
  ctx.fill(path);

  // demo only
  ctx.beginPath();
  ctx.arc(centroid.x, centroid.y, 50, 0, Math.PI*2)
  ctx.stroke();
  
  angle++;
  requestAnimationFrame( rotate );
}
<canvas id="canvas" width="1800" height="700"></canvas>

关于javascript - 以自身为中心旋转一个三 Angular 形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58213344/

相关文章:

drag-and-drop - kineticjs 将图像从 dom 拖放到 Canvas 中

javascript - 用于使用 jquery ui 调整大小的 Angular js 指令无法设置最大宽度

javascript - 在 Canvas 元素中对模拟渐变进行动画处理时的随机图案

javascript - 有没有办法进一步简化这些 javascript 函数?

javascript - html/javascript Canvas drawImage无需2次加载

javascript - 在 javascript 和 Html5 中从 Array 创建图像

javascript - 带有 jQ​​uery 和 textarea 的动态 if/else 语句

javascript - 如何将 graphql 查询发送到远程 url?

javascript - Apache 2 : Access files within another directory than/var/www

javascript - Rest Api 参数验证最佳实践