在这个实例中,只有一个draw这一个函数。这个函数的功能是把canvas画布的背景用浅蓝色布满,然后画出一个边框为红色的橙色长方形。
用canvas元素绘制矩形的脚本文件:
<!DOCTYPE html> <head> <meta charset="UTF-8" /> <script> function draw(id) { var canvas = document.getElementById(id); if (canvas == null) return false; var context = canvas.getContext('2d'); context.fillStyle = "#EEEEFF"; context.fillRect(0, 0, 336, 90); context.fillStyle = "#ffb244"; context.strokeStyle = "#bb1508"; context.lineWidth = 10; context.fillRect(15, 15, 220, 60); context.strokeRect(15, 15, 220, 60); } </script> </head> <body> <canvas/> </body> </html>1.取得canvas元素用document.getElementById等方法取得canvas对象。因为需要调用这个对象提供的方法来进行图形绘制。
2.取得上下文(context)图像上下文(graphics context)封装了很对绘图功能对象,需要使用canvas对象的getContext方法来获得图形上下文。在draw函数中,将参数设为“2d”。
3.填充与绘制边框用canvas元素绘制图形的时候,有两种方式——填充(fill)与绘制边框(stroke)。填充是指填满图形内部;绘制边框是指只绘制外框。canvas元素结合使用这种方式来绘制图形。
4.设定绘图样式(style)在进行图形绘制的时候,首先要设定好绘制图的样式(style),然后调用有关方法进行图形的绘制。
设定填充图形的样式fillStyle——填充的样式。
设定图形边框样式strokeStyle——图形边框样式。
5.指定线宽使用图形上下文对象的lineWidth属性设置图形边框的宽度。在绘制图形的时候,任何直线都可以通过lineWidth属性来指定直线的宽度。
6.指定颜色值分别用fillStyle属性和strokeStyle属性来指定填充的颜色或边框颜色。
7.绘制矩形分别使用fillRect方法与strokeRect方法来填充矩形和绘制矩形边框。
context.fillRect(x,y,width,height) context.strokeRect(x,y,width,height)通过getContext来获得图形上下文,通过fillStyle属性与strokeStyle属性来指定颜色,通过fillRect方法与strokeRect方法来绘制图形,就可以绘制出简单的图形了。