在Canvas

时间:2017-01-21 14:07:22

标签: javascript html5 canvas

现在我正在玩Canvas及其功能,但是我遇到了一个奇怪的问题。我目前正试图在由几个" lineTo"组成的三角形内画一个圆圈。我的问题是当我刚刚实现弧形时;它绘制圆形,但是从中心向外,向右侧(角度0)。如果我将我的弧括在beginPath和closePath中,它会完美地绘制它,但是Triangle会消失(提供JSFiddle)。为什么发生这种情况我也做了一些特别错误的事情?我是Canvas的新手,我想学习,提前谢谢你!

JSFIDDLE https://jsfiddle.net/720hg2aq/1/

// Draw Triangle
ctx.moveTo((width*0.4), (height*0.05));
ctx.lineTo((width*0.6), (height*0.05));

ctx.moveTo((width*0.6), (height*0.05));
ctx.lineTo((width*0.5), (height*0.15));

ctx.moveTo((width*0.5), (height*0.15));
ctx.lineTo((width*0.4), (height*0.05));

ctx.moveTo((width*0.5), (height*0.09));
// End of Triangle

// Begin Circle
ctx.beginPath();
ctx.arc((width*0.5), (height*0.09), 20, 0 , 2 * Math.PI);
ctx.closePath();
// End Circle

// Draw it out
ctx.strokeStyle = '#000';
ctx.stroke();

1 个答案:

答案 0 :(得分:1)

beginPath()方法开始路径,或重置当前路径

开始路径后,使用moveTo()lineTo()quadricCurveTo()bezierCurveTo()arcTo()arc()来制作路径,然后storke()它。

所以代码应该是:

ctx.strokeStyle = "black";

// Draw Triangle
ctx.beginPath(); /// Let's start the work!
ctx.moveTo((width*0.4), (height*0.05));
ctx.lineTo((width*0.6), (height*0.05));

ctx.moveTo((width*0.6), (height*0.05));
ctx.lineTo((width*0.5), (height*0.15));

ctx.moveTo((width*0.5), (height*0.15));
ctx.lineTo((width*0.4), (height*0.05));

ctx.moveTo((width*0.5), (height*0.09));
ctx.stroke(); /// Brushing with your dye!!
// End of Triangle

// Begin Circle
ctx.beginPath(); /// Let's start the **NEW** work!
/// Don't let the previous path be connected with the current path!
ctx.arc((width*0.5), (height*0.09), 20, 0 , 2 * Math.PI);
ctx.closePath();
ctx.stroke(); /// Brushing with your dye!!
// End Circle