如何在html画布中使用bezierCurveTo绘制螺旋线?

问题描述 投票:0回答:1

我想画一个螺旋,一个半径随着角度稳定增加的圆。

搜索类似问题时,总是通过用

lineTo
方法画很多条线来近似圆形/螺旋。使用的线条越多,圆/螺旋就越接近。但使用大量线路会带来性能劣势,因此程序员需要权衡“性能”与“外观”。

另一方面,

bezierCurveTo
可以画出完美的螺旋,没有巨大的性能劣势,但我不知道如何计算贝塞尔方法的控制点。

使用

lineTo
方法绘制螺旋的 Playground:JSFiddle Playground

context.save();
context.beginPath();
let offset = initialRadius;
for (let turn = 0; turn < turnCount; turn++) {
    for (let step = 0; step < stepCount; step++) {
        context.lineTo(offset, 0);
        offset += growthPerTurn / stepCount;
        context.rotate(360 / stepCount * Math.PI / 180);
    }
}
context.lineWidth = 3;
context.strokeStyle = "yellow";
context.stroke();
context.restore();
javascript html html5-canvas spiral
1个回答
0
投票

更数学的方法怎么样:

var ctx = document.getElementById("c").getContext("2d");

var diam = 80
var frame = 0

function drawDot(x, y) {
  ctx.beginPath();
  ctx.arc(x, y, 1, 0, 2 * Math.PI);
  ctx.stroke();
}

function loop() {
  let angle = (frame++ % 360)
  let a = angle * Math.PI / 180
  drawDot(100 + diam * Math.cos(a), 100 + diam * Math.sin(a))
  diam -= 0.05
  if (diam < 20) clearInterval(inter)
}

inter = setInterval(loop, 10);
<canvas id="c" width=200 height=200></canvas>

© www.soinside.com 2019 - 2024. All rights reserved.