1.canvas元素基础知识
(1)在页面上放置canvas元素,相当于在页面上放置一块“画布”,可以用Javascript编写在其中进行绘画的脚本。
(2)在页面中放置canvas元素
eg:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> <script type="text/javascript" src="script.js" charset="gb2312"></script> </head> <body onload="draw('canvas');"> <h1>元素标签</h1> <canvas id="canvas" width="400" height="300"></canvas> </body> </html>
function draw(id){ var canvas=document.getElementById(id); if(canvas==null){ return false; } var context=canvas.getContext("2d"); context.fillStyle="#eeeeff"; //fillStyle:填充的样式,在该属性中填入填充的颜色。 context.fillRect(0,0,400,300); //fillRect方法,填充矩形。 context.fillStyle="red"; context.strokeStyle="bule"; //strokeStyle:图形边框的样式,边框的颜色。 context.lineWidth=1; //线宽。 context.fillRect(50,50,100,100); context.strokeRect(50,50,100,100); //strokeRect:绘制矩形边框。 context.clearRect(60,60,50,50); //clearRect:将指定的矩形区域中的图形擦除,变为透明。 }
如上程序,使用canvas和Javascript脚本绘制矩形,步骤如下:
(1)取得canvas元素,用document.getElementById等方法取得canvas对象。
(2)取得上下文(context)
进行图形绘制时,需要使用到图形上下文,图形上下文是一个封装了很多绘图功能的对象。需要使用canvas对象的getContext方法获取图形的上下文。在draw函数中,将参数设置为2d。
(3)填充和绘制边框。
(4)使用fillStyle和strokeStyle设定图形和边框的样式。
(5)使用fillRect和strokeRect方法绘制矩形和边框。
注:
context.fillRect(x,y,width,height)
context.strokeRect(x,y,width,height)
context.clearRect (x,y,width,height) 三个方法的参数是一样的,x是指矩形起点的横坐标,y是指矩形起点的纵坐标,坐标原点为canvas画布的最左上角,width是指矩形的长度,height是指矩形的高度——通过这4个参数,矩形的大小可以同时确定。