繁体   English   中英

围绕自定义中心旋转自定义画布对象

[英]Rotate Custom Canvas Object around its own center

我创建了一些函数,这些函数将绘制矩形,圆形,六边形等。其中一个看起来像这样:

rotation = 0;
function hex(hex_sides, hex_size, hex_color){
  x = ctx.canvas.width/2;
  y = ctx.canvas.height/2;

  ctx.save();
  ctx.translate(x,y);
  ctx.rotate(rotation*Math.PI/180);
  //ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
  ctx.moveTo(0,0);
  for (i = 0; i < hex_sides+1; i++) {
    ctx.lineTo(x + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
  }
  ctx.strokeStyle = hex_color;
  ctx.stroke();
  ctx.restore();
}

现在,我在动画循环中调用“绘制形状的函数”。

function loop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  circle(200);
  circle(220);
  hex(6, 180, "#fff");
  rotation += 0.4;
  requestAnimationFrame(loop);
}

这里的问题是我无法使“自定义形状”(六边形)围绕中心(其自身的轴)旋转。 我已经弄清楚它与translate()和绘制线条的for循环有关。

同样,整个代码在这里。

没关系...弄清楚了,我忘了从平移点减去形状宽度的一半,而且顺序似乎比我更重要。

工作守则

function hex(hex_sides, hex_size, hex_color){
    x = ctx.canvas.width/2;
    y = ctx.canvas.height/2;

    ctx.save();
    ctx.translate(x,y);
    ctx.rotate(rotation*Math.PI/180);
    //ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
    ctx.moveTo(0,0);
    for (i = 0; i < hex_sides+1; i++) {
        ctx.lineTo(x/hex_size + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y/hex_size + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
    }
    ctx.strokeStyle = hex_color;
    ctx.stroke();
    ctx.restore();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM