本文摘自PHP中文网,作者巴扎黑,侵删。
<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基本绘图之绘制矩形的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
html5 footer标签怎么用?footer标签的用法实例
更多相关阅读请进入《矩形》频道 >>

Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者