您好,欢迎访问一九零五行业门户网

HTML5 canvas基本绘图之绘制矩形

<canvas></canvas>是html5中新增的标签,用于绘制图形,这篇文章主要为大家详细介绍了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复制内容到剪贴板
<script type="text/javascript">   
    var canvas = document.getelementbyid(canvas);   
    var context = canvas.getcontext(2d);
//使用rect方法   
    context.rect(10,10,190,190);   
    context.linewidth = 2;   
    context.fillstyle = #3ee4cb;   
    context.strokestyle = #f5270b;   
    context.fill();   
    context.stroke();
//使用fillrect方法   
    context.fillstyle = #1424de;   
    context.fillrect(210,10,190,190);
//使用strokerect方法   
    context.strokestyle = #f5270b;   
    context.strokerect(410,10,190,190);
//同时使用strokerect方法和fillrect方法   
    context.fillstyle = #1424de;   
    context.strokestyle = #f5270b;   
    context.strokerect(610,10,190,190);   
    context.fillrect(610,10,190,190);   
</script>
这里需要说明两点:第一点就是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);
可以得到以下效果:
以上就是html5 canvas基本绘图之绘制矩形的详细内容。
其它类似信息

推荐信息