围绕三角形画布旋转圆

围绕三角形画布旋转圆

本文介绍了围绕三角形画布旋转圆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to spin a circle around a triangle using canvas. Have this code from earlier, but here is the circle in the middle, and a rectangle spinning, i want the circle to spin and have a triangle in the middle. Can someone help?

这是我拥有的JS代码:

Here is the JS code i have:

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>

推荐答案

我已经编辑了您的代码以绘制所需的形状,并添加了注释以描述我在下面的代码段中所做的事情.

I have edited your code to draw the requested shapes and added comments to describe, what i am doing in the snippet below.

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的官方画布教程.

It sounds like you lack experience with HTML Canvas manipulation, so i would like to recommend some MDN's official canvas tutorial.

如果您还有其他问题,请随时提出带有更多特定于代码的问题的新问题.

If you have further questions feel free to open new questions with more code-specific problems in the future.

这篇关于围绕三角形画布旋转圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:44