HTML5 规范引进了很多新特性,其中最令人期待的之一就是 canvas 元素。HTML 5 canvas 提供了通过 JavaScript 绘制图形的方法,此方法使用简单但功能强大。每一个 canvas 元素都有一个”上下文( context )” (想象成绘图板上的一页),在其中可以绘制任意图形。浏览器支持多个 canvas 上下文,并通过不同的 API 提供图形绘制功能。大部分的浏览器都支持 2D canvas 上下文——包括 Opera, Firefox, Konqueror 和 Safari。而且某些版本的 Opera 还支持 3D canvas ,Firefox 也可以通过插件形式支持 3D canvas。
-创建 canvas 的方法很简单,只需要在 HTML 页面中添加 <canvas>元素:
1
2
3
|
|
创建好了画布后,让我们来准备画笔。要在画布中绘制图形需要使用 JavaScript 。首先通过 getElementById函数找到 canvas元素,然后初始化上下文。之后可以使用上下文 API 绘制各种图形。下面的脚本在 canvas 中绘制一个矩形 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
|