canvas绘制矩形的方法,使用canvas绘制图形,下面哪个方法可以绘制矩形-_1

  canvas绘制矩形的方法,使用canvas绘制图形,下面哪个方法可以绘制矩形?

  canvas/canvas只是一个绘制图形的容器。除了id,class,style等属性,还有高度和宽度属性。在画布上绘制元素有三个主要步骤:

  1.获取canvas元素对应的DOM对象,这是一个Canvas对象;

  2.调用CanvasRenderingContext2D对象的getContext()方法;

  3.调用CanvasRenderingContext2D对象进行绘制。

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

  context.rect( x,y,width,height):只定义矩形的路径;

  Context.fillrect (x,y,width,height):直接绘制填充的矩形;

  Context.strokerect (x,y,width,height):直接画一个矩形边框;

  代码将内容复制到剪贴板script type= text/JavaScript var canvas=document . getelementbyid( canvas );var context=canvas . get context( 2d );//使用rect方法context.rect(10,10,190,190);context . line width=2;context . fill style= # 3ee 4cb ;context . stroke style= # f 5270 b ;context . fill();context . stroke();//使用fillRect方法context . fill style= # 1424 de ;context.fillRect(210,10,190,190);//使用strokeRect方法context . stroke style= # f 5270 b ;context.strokeRect(410,10,190,190);//同时使用strokeRect方法和fillRect方法context . fill style= # 1424 de ;context . stroke style= # f 5270 b ;context.strokeRect(610,10,190,190);context.fillRect(610,10,190,190);/脚本

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

  还有一个和矩形绘制有关:clear rectangle area:context . clear rect(x,y,width,height)。

  接收参数是:清除矩形的起始位置以及矩形的宽度和长度。

  在上面的代码中,添加:

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

  可以获得以下效果:

  这就是本文的全部内容。希望对大家的学习和支持有帮助。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: