1 <style> 2 body { 3 background: #000; 4 } 5 #canvas{ 6 background:white; 7 } 8 </style> 9 <script> 10 window.onload = function(){ 11 var oCanvas = document.querySelector( "#canvas" ), 12 oGc = oCanvas.getContext( '2d' ); 13 14 oGc.moveTo( 50, 50 ); 15 oGc.lineTo( 250, 50 ); 16 oGc.lineTo( 250, 150 ); 17 oGc.closePath(); 18 oGc.stroke(); 19 } 20 </script> 21 </head> 22 <body> 23 <canvas></canvas> 24 </body>
在stroke之前,用closePath关闭路径,他就会把( 250, 150)这个点和起始点( 50, 50 )连接起来.
画2个三角形:
1 var oCanvas = document.querySelector( "#canvas" ), 2 oGc = oCanvas.getContext( '2d' ); 3 4 oGc.moveTo( 50, 50 ); 5 oGc.lineTo( 250, 50 ); 6 oGc.lineTo( 250, 150 ); 7 oGc.closePath(); 8 oGc.stroke(); 9 10 oGc.moveTo( 50, 150 ); 11 oGc.lineTo( 250, 150 ); 12 oGc.lineTo( 250, 250 ); 13 oGc.closePath(); 14 oGc.stroke();
使用路径,绘制两个不同颜色的三角形:
1 <style> 2 body { 3 background: #000; 4 } 5 #canvas{ 6 background:white; 7 } 8 </style> 9 <script> 10 window.onload = function(){ 11 var oCanvas = document.querySelector( "#canvas" ), 12 oGc = oCanvas.getContext( '2d' ); oGc.beginPath(); 16 oGc.strokeStyle = 'red'; 17 oGc.moveTo( 50, 50 ); 18 oGc.lineTo( 250, 50 ); 19 oGc.lineTo( 250, 150 ); 20 oGc.closePath(); 21 oGc.stroke(); 22 23 oGc.beginPath(); 24 oGc.strokeStyle = '#09f'; 25 oGc.moveTo( 50, 150 ); 26 oGc.lineTo( 250, 150 ); 27 oGc.lineTo( 250, 250 ); 28 oGc.closePath(); 29 oGc.stroke(); 30 } 31 </script> 32 </head> 33 <body> 34 <canvas></canvas> 35 </body>