javascript - 圆没有使用 Canvas 正确地通过线连接

标签 javascript html canvas html5-canvas

我正在尝试创建 11 个圆圈,这些圆圈通过线与中间的圆圈连接。我正在尝试画圆圈。在这里我做了一些研发,但我无法制作线条。请帮我完成这个。

 var canvas, ctx;
        var circlePoints = [];
        function createCanvasPainting() {
            
            canvas = document.getElementById('myCanvas');
            if (!canvas || !canvas.getContext) {
                return false;
            }
            canvas.width = 600;
            canvas.height = 600;
            ctx = canvas.getContext('2d');           
            ctx.strokeStyle = '#B8D9FE';
            ctx.fillStyle = '#B8D9FE';
            ctx.translate(300, 250);
            ctx.arc(0, 0, 50, 0, Math.PI * 2); //center circle
            ctx.stroke();
            ctx.fill();
            var angleRotate = 0;
            for (var i=0; i<11; i++) {
                if (i > 0) {
                    angleRotate += 32.72;
                }
                lineToAngle(ctx, 0, 0, 200, angleRotate);
            }
        }

        function lineToAngle(ctx, x1, y1, length, angle) {

            angle *= Math.PI / 180;

            var x2 = x1 + length * Math.cos(angle),
            y2 = y1 + length * Math.sin(angle);
            ctx.beginPath();
            ctx.moveTo(x1, y1);
            ctx.lineTo(x2, y2);
            ctx.lineWidth = 1;
            ctx.arc(x2, y2, 40, 0, Math.PI * 2);
            ctx.fill();
            ctx.stroke();

            circlePoints.push({x: x2, y: y2});
            // console.log(circlePoints);
        }

        createCanvasPainting();
<canvas id="myCanvas"></canvas>

Here is my JSFiddle Link

最佳答案

请参阅下文,我从您的代码中删除了所有“噪音”。
只是圆圈与中间圆圈相连的线。

canvas = document.getElementById('myCanvas');
canvas.width = canvas.height = 200;
ctx = canvas.getContext('2d');
ctx.lineWidth = 1;
ctx.translate(99, 99);
angle = 0;

function draw() {
  ctx.clearRect(-99, -99, 200, 200);
  ctx.beginPath();
  ctx.arc(0, 0, 35 + Math.cos(angle / 3000), 0, Math.PI * 2);
  ctx.stroke();
  ctx.fill();

  for (var i = 0; i < 11; i++) {
    a = angle * Math.PI / 180;
    x = 80 * Math.cos(a)
    y = 80 * Math.sin(a)
    ctx.beginPath();
    ctx.arc(x, y, 18, 0, Math.PI * 2);
    ctx.moveTo(x, y);
    ctx.lineTo(0, 0);
    ctx.fill();
    ctx.stroke();
    angle += 32.7;
  }
}

setInterval(draw, 10);
<canvas id="myCanvas"></canvas>

关于javascript - 圆没有使用 Canvas 正确地通过线连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60473417/

相关文章:

javascript - 在页面加载时检索数据库记录而不是 JavaScript 中的 keyup 函数

javascript - 查找数组中的某些字符串(Javascript)

javascript - jQuery 从类中附加元素

html - Bootstrap 和 flexbox - 在移动设备上将三个 `.col-md-3` 折叠成单列

javascript - $(window).resize() 和 $(document).ready() 计算不同的值

HTML5 Canvas 检查器?

javascript - 如何使用 Cocos2D 制作 HTML5 Canvas 整页大小

javascript - 在自动完成 jQuery UI 中显示数据

javascript - 将视频添加到 YouTube 上用户的收藏夹/喜欢的播放列表

Html Canvas - 翻译、旋转、剪辑 - 使用 context.restore 更快地恢复