html5-canvas beginPath(路径命令)
示例
context.beginPath()
开始组装一组新的路径命令,也丢弃任何先前组装的路径。
还将图形“笔”移动到画布的左上角原点(==coordinate[0,0])。
尽管是可选的,但您应该始终使用beginPath
丢弃是一个重要且经常被忽视的问题。如果您不使用来开始新路径beginPath,则任何先前发出的路径命令都将自动重绘。
这两个演示都试图用一个红色描边和一个蓝色描边绘制一个“X”。
这个第一个演示正确地用于beginPath开始第二个红色描边。结果是“X”正确地具有红色和蓝色笔划。
<!doctype html> <html> <head> <style> body{ background-color:white; } #canvas{border:1px solid red; } </style> <script> window.onload=(function(){ //获取对canvas元素及其上下文的引用 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); //画一条蓝线 ctx.beginPath(); ctx.moveTo(30,30); ctx.lineTo(100,100); ctx.strokeStyle='blue'; ctx.lineWidth=3; ctx.stroke(); //画一条红线 ctx.beginPath(); //重要的是要开始一条新的道路! ctx.moveTo(100,30); ctx.lineTo(30,100); ctx.strokeStyle='red'; ctx.lineWidth=3; ctx.stroke(); }); //结束window.onload </script> </head> <body> <canvas id="canvas" width=200 height=150></canvas> </body> </html>
第二个演示错误地beginPath在第二个笔画中遗漏了。结果是“X”错误地同时出现了两个红色笔触。
第二个stroke()是绘制第二个红色笔画。
但是如果没有秒beginPath,则同一秒stroke()也将错误地重画第一笔画。
由于stroke()现在将第二个样式设置为红色样式,因此第一个蓝色笔画将被错误地着色的红色笔画覆盖。
<!doctype html> <html> <head> <style> body{ background-color:white; } #canvas{border:1px solid red; } </style> <script> window.onload=(function(){ //获取对canvas元素及其上下文的引用 var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); //画一条蓝线 ctx.beginPath(); ctx.moveTo(30,30); ctx.lineTo(100,100); ctx.strokeStyle='blue'; ctx.lineWidth=3; ctx.stroke(); //画一条红线 //注意:缺少必要的“beginPath”! ctx.moveTo(100,30); ctx.lineTo(30,100); ctx.strokeStyle='red'; ctx.lineWidth=3; ctx.stroke(); }); //结束window.onload </script> </head> <body> <canvas id="canvas" width=200 height=150></canvas> </body> </html>