1 <script> 2 window.onload = function(){ 3 var oCanvas = document.querySelector( "#canvas" ), 4 oGc = oCanvas.getContext( '2d' ); 5 6 oGc.strokeStyle = '#09f'; 7 oGc.strokeRect( 50, 50, 500, 300 ); 8 } 9 </script> 10 </head> 11 <body> 12 <canvas></canvas> 13 </body>
注意:oGc.strokeStyle = '#09f'; 如果把这句代码放在oGc.strokeRect( 50, 50, 500, 300 );的后面,那么设置的线条样式将不会生效,strokeStyle一定要在画图之前设置,否则是不会应用到的
填充矩形API
cxt.fillStyle = 属性值;
cxt.fillRect( x, y, width, height );
跟上面是一样的,只是把stoke换成了fill,fill就是填充的意思
画一个带有透明度的矩形:
1 <script> 2 window.onload = function(){ 3 var oCanvas = document.querySelector( "#canvas" ), 4 oGc = oCanvas.getContext( '2d' ); 5 6 oGc.fillStyle = 'rgba( 255, 0, 0, 0.3 )'; 7 oGc.fillRect( 50, 50, 500, 300 ); 8 } 9 </script> 10 </head> 11 <body> 12 <canvas></canvas> 13 </body>
另一种绘制矩形的API:cxt.rect( x, y, width, height );
他与strokeRect和fillRect有什么区别呢?
1,共同点:参数的意思相同
2,不同点,调用strokeRect和fillRect会立即绘制出矩形,而rect并不会,他需要调用stoke()或者fill()方法,才能把矩形绘制出来
1 <script> 2 window.onload = function(){ 3 var oCanvas = document.querySelector( "#canvas" ), 4 oGc = oCanvas.getContext( '2d' ); 5 6 oGc.fillStyle = 'rgba( 255, 0, 0, 0.3 )'; 7 oGc.rect( 50, 50, 500, 300 ); oGc.fill(); 10 } 11 </script> 12 </head> 13 <body> 14 <canvas></canvas> 15 </body>
清空矩形API:cxt.clearRect( x, y, width, height ); 参数跟strokeRect,fillRect意思一样
1 <script> 2 window.onload = function(){ 3 var oCanvas = document.querySelector( "#canvas" ), 4 oGc = oCanvas.getContext( '2d' ); 5 6 oGc.fillStyle = 'rgba( 255, 0, 0, 0.3 )'; 7 oGc.fillRect( 50, 50, 500, 300 ); 8 9 oGc.clearRect( 100, 100, 200, 200 ); 10 } 11 </script> 12 </head> 13 <body> 14 <canvas></canvas> 15 </body>
用fillRect和clearRect画一个加号,当然你可以用moveTo和lineTo,不过代码应该比这种方法多了不少.
1 <script> 2 window.onload = function(){ 3 var oCanvas = document.querySelector( "#canvas" ), 4 oGc = oCanvas.getContext( '2d' ); 5 6 oGc.fillStyle = 'rgba( 255, 0, 0, 0.3 )'; 7 oGc.fillRect( 100, 100, 200, 200 ); 8 oGc.clearRect( 100, 100, 50, 50 ); 9 oGc.clearRect( 250, 100, 50, 50 ); 10 oGc.clearRect( 250, 250, 50, 50 ); 11 oGc.clearRect( 100, 250, 50, 50 ); 12 } 13 </script> 14 </head> 15 <body> 16 <canvas></canvas> 17 </body>
绘制一个调色板: