画布路径到底是什么,ctx.closePath()的用途是什么?

Aro*_*ano 25 javascript html5 drawing canvas jcanvas

我正在开发HTML5游戏.我需要在画布上绘制尾线并检查游戏中的交叉点,这是一个Tron风格的游戏.

我实际上是在使用JCanvas中drawLine()函数,但是JCanvas没有为我提供检查行交集的方法,我挖掘了源代码并发现使用了ctx对象,并且在我使用的函数的最后,我返回了对象,所以我可以使用该ctx.isPointInPath()方法来实现我需要的,但不工作,false每次都返回...

我真的不明白路径是什么 - 只ctx.isPointInPath()返回true使用ctx.moveTo()after 设置的点ctx.beginPath()?或者它将返回true连续ctx.moveTo()使用2个连续s 之间的所有点ctx.lineTo()

有什么用ctx.closePath()

有什么区别:

{
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}
Run Code Online (Sandbox Code Playgroud)

和:

{
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
}
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 53

什么是路径?

它是一系列路径命令(moveTo,lineTo,arcTo等),用于定义矢量形状的边界.然后,您可以根据需要填充和/或描边路径.

有什么用closePath()

演示:http://jsfiddle.net/YrQCG/5/

// Draw a red path using closePath() in the middle
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(50,100);
ctx.lineTo(100,150);
ctx.lineTo(150,100);
ctx.closePath();
ctx.lineTo(50,50);
ctx.stroke();

// Slide the next path over by 150 pixels    
ctx.translate(150,0);

// Draw a blue path using the exact same commands, but without closePath
ctx.beginPath();
ctx.strokeStyle = 'blue';
ctx.moveTo(50,100);
ctx.lineTo(100,150);
ctx.lineTo(150,100);
//ctx.closePath();
ctx.lineTo(50,50);
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)

                                          在此输入图像描述

使用closePath()导致笔的点移回当前子路径的开始,从当前点绘制一条线回到该起始点 ; 下一个命令从这个新点开始.如果要绘制完全轮廓的形状而不显式绘制最后一行,这将非常有用.

它相当于lineTo()使用当前子路径的第一个点的位置进行调用,然后调用moveTo()该相同的点(以建立新的子路径).

  • 如上所示,我们V使用第一个moveTo和后面两个lineTo命令绘制符号.当我们调用closePath红色路径时,它会绘制水平条,并使下一条线从左上角开始.

  • 当我们不在closePath蓝色路径中调用时,下一个lineTo命令将从最后一个绘制点继续.

请注意,closePath()没有必要的大部分时间,不像beginPath()你必须要开始绘制新的路径,每次打电话.(如果不这样做,则所有旧路径绘制命令都是下一个绘图的一部分.)


小智 15

这是封闭路径的基本表示:

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,0);
ctx.lineTo(100,100);
ctx.lineTo(0,100);    
ctx.closePath(); // <--the image right side has this line
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)

结果closePath()是起点和终点都是有界的.

封闭的道路