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 ):直接绘制出矩形边框;
- <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);
可以得到以下效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
最后更新于 2021-10-23 07:49:28 并被添加「」标签,已有 位童鞋阅读过。
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处
相关文章
- 虚拟机怎么安装Ubuntu 15.04试用?
- python实现凯撒密码
- 比较简单的CentOS服务器安装方法小结 推荐
- 怎么用OneKey Ghost安装系统 onekey ghost安装win7详细图文步骤
- C语言输入1000以下的正整数(C语言输入1000以下的正数)。