围绕三角形画布旋转圆

KX0

我想使用画布在三角形周围旋转一个圆。早先有这段代码,但是这里是中间的圆圈,还有一个旋转的矩形,我希望圆圈旋转并在中间有一个三角形。有人可以帮忙吗?

这是我拥有的JS代码:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cx = 100;
var cy = 100;
var rectWidth = 15;
var rectHeight = 10;
var rotation = 0;
requestAnimationFrame(animate);

function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(cx, cy, 10, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fill();
  ctx.save();
  ctx.translate(cx, cy);
  ctx.rotate(rotation);
  ctx.strokeRect(-rectWidth / 2 + 20, -rectHeight / 2, rectWidth, rectHeight);
  ctx.restore();

  rotation += Math.PI / 180;
}
<canvas id="canvas"></canvas>

埃米尔·S·约根森

我已经编辑了您的代码以绘制所需的形状,并添加了注释来描述我在以下代码段中所做的工作。

var canvas = document.body.appendChild(document.createElement("canvas"));
var ctx = canvas.getContext("2d");
var cx = 100;
var cy = 100;
var rotation = 0;
requestAnimationFrame(animate);
function animate() {
    //Clear canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    //Draw center figure
    /*
    ctx.beginPath();
    ctx.arc(cx, cy, 10, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    */
    ctx.beginPath();
    ctx.moveTo(cx - 10, cy - 10);
    ctx.lineTo(cx, cy + 10);
    ctx.lineTo(cx + 10, cy - 10);
    ctx.closePath();
    ctx.fill();
    //Rotate canvas
    ctx.save();
    ctx.translate(cx, cy);
    ctx.rotate(rotation);
    //Draw rotating object
    /*ctx.strokeRect(-rectWidth / 2 + 20, -rectHeight / 2, rectWidth, rectHeight);*/
    ctx.beginPath();
    ctx.arc(20, 0, 5, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
    //Rotate canvas back
    ctx.restore();
    //Save rotation
    rotation += Math.PI / 180;
    //Request next frame
    requestAnimationFrame(animate);
}

听起来您缺乏HTML Canvas操作经验,所以我想向您推荐MDN的官方canvas教程

如果您还有其他问题,请随时打开新问题,以解决更多特定于代码的问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章