在路径中绘制不同颜色的形状(HTML5 Canvas / Javascript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7184475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:14:24  来源:igfitidea点击:

Drawing different colored shapes in a path (HTML5 Canvas / Javascript)

javascripthtmlcanvasdraw

提问by jondavidjohn

I'm trying to draw multiple circle arcs filled with different colors

我正在尝试绘制多个填充不同颜色的圆弧

        //-------------- draw
        ctx.beginPath();
        ctx.fillStyle = "black";
        ctx.arc(30, 30, 20, 0, Math.PI*2, true);
        ctx.fill();
        ctx.fillStyle = "red";
        ctx.arc(100, 100, 40, 0, Math.PI*2, true);
        ctx.fill();
        ctx.closePath();

This produces both arcs filled in with red, and I can tell that there is a faint black outline around the smaller one.

这会产生两个用红色填充的弧线,我可以看出较小的弧线周围有一个微弱的黑色轮廓。

enter image description here

在此处输入图片说明

Can anyone shed some light on how I can accomplish this? what I'm doing wrong?

任何人都可以阐明我如何实现这一目标吗?我做错了什么?

回答by alex

Close the path and then reopen it.

关闭路径,然后重新打开它。

ctx.closePath();
ctx.beginPath();

jsFiddle.

js小提琴

...between the arc drawing code.

...在圆弧绘制代码之间。

Circles

界

回答by neticous

A path starts with beginPath and ends with endPath. Every thing in between is the same path. You can even draw paths with holes in them by using winging rules. Draw something in one direction and something else the opposite direction but inside the first thing. Let's draw a rectangle with a hole in the middle using lines. beginPath(); moveTo (10,10); lineTo(100,10); lineTo((100,60); lineTo(10,60); lineTo(10,10); closePath(); moveTo(20,20); lineTo(20,50); lineTo(90,50); lineTo(90,20); lineTo(20,20); closePath(); endPath(); fill();

路径以 beginPath 开始,以 endPath 结束。两者之间的每件事都是相同的路径。您甚至可以使用翼形规则绘制带有孔洞的路径。在一个方向画一些东西,在相反的方向画一些东西,但在第一件事里面。让我们用线条画一个中间有洞的矩形。开始路径();移动到(10,10);lineTo(100,10); lineTo((100,60); lineTo(10,60); lineTo(10,10); closePath(); moveTo(20,20); lineTo(20,50); lineTo(90,50); lineTo(90) ,20); lineTo(20,20); closePath(); endPath(); fill();

You could do this with any shape. Try an arc in one direction then another in the opposite direction using a smaller radius

你可以用任何形状来做到这一点。使用较小的半径在一个方向尝试一个弧,然后在相反方向尝试另一个