我正在javascript画布上绘制一个实心椭圆(使用arc()):
ctx.arc(centerX, centerY, dotDiameter / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = color1;
ctx.fill();然后我想画一条线,它被剪裁到这个椭圆上,用不同的颜色。
ctx.clip(); // Clip to the ellipse
ctx.strokeStyle = color2;
ctx.moveTo(centerX - dotRadius, centerY);
ctx.lineTo(centerX + dotRadius, centerY);
ctx.stroke();但是,椭圆也使用color2描边。
如何才能将线裁剪到椭圆,而不对椭圆进行描边?在我调用clip()之后,有没有办法从画布上删除这个椭圆(也就是圆弧)?
谢谢!
(仅供参考,这是对我的代码的过度简化。描边的线条比一条水平线更复杂,并且需要裁剪线条。)
发布于 2020-04-01 02:05:27
我们可以用一些基本的三角来计算椭圆周长上的一个点。
ctx.moveTo(x, y);
x += radiusX * Math.cos(lineangle)
y += radiusY * Math.sin(lineangle)
ctx.lineTo(x, y);参见下面的代码片段,我正在绘制一个椭圆和一条从中心到边缘的直线。
ctx = document.getElementById('c').getContext('2d');
ctx.lineWidth = 2;
function draw(x, y, radiusX, radiusY, lineangle, color1, color2) {
ctx.beginPath()
ctx.ellipse(x, y, radiusX, radiusY, 0, 0, 2 * Math.PI, false);
ctx.fillStyle = color1;
ctx.fill();
ctx.beginPath()
ctx.strokeStyle = color2;
ctx.moveTo(x, y);
x += radiusX * Math.cos(lineangle)
y += radiusY * Math.sin(lineangle)
ctx.lineTo(x, y);
ctx.stroke();
}
angle = 0
function loop() {
ctx.clearRect(0,0, 500, 500);
draw(80, 80, 70, 50, angle, "red", "lime")
draw(240, 60, 80, 30, angle*0.7, "black", "cyan")
draw(360, 80, 30, 70, angle*2, "white", "black")
angle += 0.05
}
setInterval(loop, 100)<canvas height="160" width="500" id="c">
https://stackoverflow.com/questions/60955533
复制相似问题