canvas绘制图形
canvas元素的基础知识
在页面上放置一个canvas元素,就相当于在页面放置了一块画布,可以在其中描绘图形。事实上,canvas元素只是一个无色透明的区域,需要利用JavaScript编写在其中进行绘画的脚本。
在页面放置canvas元素
首先要指定的是ID、width、height三个属性
<canvas id="canvas" width="400" height="300" />
绘制矩形
- 取得canvas元素,用document.getElementById()方法
- 取得上下文(context),用getContext()方法
- 填充与绘制边框,填充(fill)、绘制边框(stroke)
- 设定图形的样式(style),主要是针对图形的颜色。填充样式(fillStyle)、图形边框的样式(strokeStyle)
- 指定线宽,通过设定图形上下文的lineWidth属性设置图形边框的宽度。
- 指定颜色值
- 绘制矩形,使用fillRect()和strokeRect()。例如:context.fillRect(x,y,width,height);x,y指定的是矩形起点坐标;width和height指定的是矩形的宽度和高度。
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('canvas');
if(canvas == null){
return false;
}
var context = canvas.getContext('2d');
context.fillStyle = '#D2CDCD';
context.fillRect(0,0,400,300);
context.fillStyle = 'red';
context.strokeStyle = 'blue';
context.lineWidth = 1;
context.fillRect(50,