HTML5 canvas基本绘图之绘制矩形

<canvas></canvas>只是一个绘制图形的容器,除了id、class、style等属性外,还有height和width属性。在<canvas>>元素上绘图主要有三步:

1.获取<canvas>元素对应的DOM对象,这是一个Canvas对象;
2.调用Canvas对象的getContext()方法,得到一个CanvasRenderingContext2D对象;
3.调用CanvasRenderingContext2D对象进行绘图。

绘制矩形rect()、fillRect()和strokeRect()

 •context.rect( x , y , width , height ):只定义矩形的路径;
 •context.fillRect( x , y , width , height ):直接绘制出填充的矩形;
 •context.strokeRect( x , y , width , height ):直接绘制出矩形边框;

JavaScript Code复制内容到剪贴板
  1. <script type="text/javascript">   
  2.     var canvas = document.getElementById("canvas");   
  3.     var context = canvas.getContext("2d");   
  4.   
  5.     //使用rect方法   
  6.     context.rect(10,10,190,190);   
  7.     context.lineWidth = 2;   
  8.     context.fillStyle = "#3EE4CB";   
  9.     context.strokeStyle = "#F5270B";   
  10.     context.fill();   
  11.     context.stroke();   
  12.   
  13.     //使用fillRect方法   
  14.     context.fillStyle = "#1424DE";   
  15.     context.fillRect(210,10,190,190);   
  16.   
  17.     //使用strokeRect方法   
  18.     context.strokeStyle = "#F5270B";   
  19.     context.strokeRect(410,10,190,190);   
  20.   
  21.     //同时使用strokeRect方法和fillRect方法   
  22.     context.fillStyle = "#1424DE";   
  23.     context.strokeStyle = "#F5270B";   
  24.     context.strokeRect(610,10,190,190);   
  25.     context.fillRect(610,10,190,190);   
  26. </script>   
  27.   

这里需要说明两点:第一点就是stroke()和fill()绘制的前后顺序,如果fill()后面绘制,那么当stroke边框较大时,会明显的把stroke()绘制出的边框遮住一半;第二点:设置fillStyle或strokeStyle属性时,可以通过“rgba(255,0,0,0.2)”的设置方式来设置,这个设置的最后一个参数是透明度。

另外还有一个跟矩形绘制有关的:清除矩形区域:context.clearRect(x,y,width,height)。
接收参数分别为:清除矩形的起始位置以及矩形的宽和长。
在上面的代码中绘制图形的最后加上:

context.clearRect(100,60,600,100);

可以得到以下效果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关文章

发表新评论