我想画一个圆。但是,不是真的。我想要一系列暗示完整圆的弧线(线段)。它会旋转,它会很棒。但我显然做错了什么。 Please, check this fiddle: http://jsfiddle.net/utWdM/
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.lineWidth = 15;
ctx.strokeStyle = 'hsla(111, 56%, 50%, 0.67)';
ctx.beginPath();
ctx.arc(250, 250, 100, 0, Math.PI * 8 / 30);
ctx.moveTo(250, 250);
ctx.arc(250, 250, 100, Math.PI * 12 / 30, Math.PI * 20 / 30);
ctx.moveTo(250, 250);
ctx.arc(250, 250, 100, Math.PI * 24 / 30, Math.PI * 32 / 30);
ctx.moveTo(250, 250);
ctx.arc(250, 250, 100, Math.PI * 36 / 30, Math.PI * 44 / 30);
ctx.moveTo(250, 250);
ctx.arc(250, 250, 100, Math.PI * 48 / 30, Math.PI * 56 / 30);
ctx.stroke();
ctx.closePath();
}
}
draw();
我不想要从中心到圆弧起点的线(第一个没有)。 我一直在研究用 Canvas 进行基本绘图,希望有一天能了解发生了什么,但我迫不及待地想知道这种情况出了什么问题。 任何帮助,非常感谢。
最佳答案
如果你想要一点灵活的解决方案,即。如果你想改变段数、每个段的大小,那么你可以创建一个通用函数,如下所示:
/**
* ctx = context
* x / y = center
* radius = of circle
* offset = rotation in angle (radians)
* segments = How many segments circle should be in
* size = size of each segment (of one segment) [0.0, 1.0]
*/
function dashedCircle(ctx, x, y, radius, offset, segments, size) {
var pi2 = 2 * Math.PI, /// cache 2*Math.PI = 360 degrees in rads
segs = pi2 / segments, /// calc. size of each segment in rads
len = segs * size, /// calc. length of segment in rads
i = 0,
ax, ay;
ctx.save();
ctx.translate(x, y);
ctx.rotate(offset); /// rotate canvas
ctx.translate(-x, -y);
for(; i < pi2; i += segs) {
ax = x + radius * Math.cos(i); /// calculate start position of arc
ay = y + radius * Math.sin(i);
ctx.moveTo(ax, ay); /// make sure to move to beginning of arc
ctx.arc(x, y, radius, i, i + len); /// draw arc
}
ctx.restore(); /// remove rotation
}
然后在您的代码中您只需调用:
ctx.beginPath();
dashedCircle(ctx, 250, 250, 100, 0, 5, 0.7);
ctx.lineWidth = 15;
ctx.strokeStyle = 'hsla(111, 56%, 50%, 0.67)';
ctx.stroke();
/// don't closePath here
使用偏移参数可以轻而易举地旋转它:
var offset = 0;
var step = 0.03;
var pi2 = 2 * Math.PI;
(function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
dashedCircle(ctx, 250, 250, 100, offset % pi2, 5, 0.7);
ctx.stroke();
offset += step;
requestAnimationFrame(loop);
})();
关于javascript - 如何在 Canvas 元素中正确绘制带间隙的圆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21679035/