canvas JavaScript API学习(一)

canvas JavaScript API学习(一)

<canvas>是html5规范中的标签,通过JavaScript脚本可以在canvas中绘画出图形或实现动画效果。更多canvas的资料请查看:The canvas element — HTML5 (including next generation additions still in development)

写在前面
对于canvas的历史我就不多赘述,Google比我知道的多!我们直接从实例开始我们的旅程。本文虽然是讲canvas,但更多的是JavaScript内容,因此要继续下去,你需要一点JavaScript基础。现在<canvas>并没有被所有浏览器支持,你需要一些支持html5的浏览器来测试文中的例子(如:Firefox1.5+,较新版本的Safari或Chrome以及opera9+等)。本人使用的浏览器是Firefox3.6.3并在此环境下做所有测试。如果你想让ie也支持可以使用explorercanvas,用vml来描述canvas的内容,使用起来很简单,只要加入下面代码即可。

XHTML

<!–[if IE]><script src= »excanvas.js »></script><![endif]–>

Hello,canvas!
首先,我们来看一段最简单的代码

XHTML

<!DOCTYPE html><html><head><meta  charset= »utf-8″ /><title>Canvas demo</title><style type= »text/css »>canvas { border:1px #000 solid; /*width:300px; height:300px;*/}</style></head><body><h1>this is a canvas api test page!</h1><canvas id= »canvas » width= »300″ height= »300″>this browser does not support canvas…</canvas></body></html>

当你在支持html5 canvas的浏览器下查看页面的时候,你会看到一个大小为300px*300px(BTW:canvas默认大小为:300px*150px),边框为1px宽的方框,而在ie下,你只能看到一句话:this browser does not support canvas…。正如你所看到的那样,canvas跟其他标签一样,可以通过css来定义样式,也可以用它本身支持的html属性来定义宽和高。但是这里有一点需要注意:在css中为canvas定义宽高,实际是将canvas进行拉伸,因此,如果在这样的情况下在canvas中绘图,你得到的图形可能就是变形的。所以建议直接在canvas中用html属性来定义canvas的大小。

canvas with JavaScript
接下来,我们来演示如何通过JavaScript在canvas里绘图。

XHTML

<!DOCTYPE html><html><head><meta  charset= »utf-8″ /><title>Canvas javascript api demo</title><style type= »text/css »>canvas { border:1px #000 solid; /*width:300px; height:300px;*/}</style></head><body><h1>this is a canvas api test page!</h1><canvas id= »canvas » width= »300″ height= »300″>this browser does not support canvas…</canvas><script type= »text/javascript »>var $=function(id){ return document.getElementById(id);}window.onload=function(){ var ctx=$(‘canvas’).getContext(‘2d’); ctx.fillStyle=’rgba(255,0,0,1)’; ctx.fillRect (10, 10, 50, 50); ctx.fillStyle = « rgba(0, 255, 0, 0.5) »;   ctx.fillRect (30, 30, 50, 50);   ctx.fillStyle = « rgba(0, 0, 255, 0.5) »;   ctx.fillRect (50, 50, 50, 50); }</script></body></html>

canvas提供了一个接口来实现一种或多种的渲染环境(rendering context),但目前还只实现了2D渲染环境。通过这个接口,我们就可以在canvas中绘图了。那么在绘图前,我们先取得这个环境:

JavaScript

1var ctx=$(‘canvas’).getContext(‘2d’);//通过canvas的id取得canvas并调用getContext方法得到2d渲染环境,目前只有2d为有效值。

代码中getContext(‘2d’)方法返回CanvasRenderingContext2D对象,该对象拥有的方法和属性可以参考文章一开始提到的url。这里我们简单介绍fillStyle属性跟fillRect方法,更多用法我会在后面的学习中演示。

fillStyle是为当前环境配置填充颜色,它支持rgb值或rgba值或十六进制值(如:#F00),也支持hsl或hsla值,默认为黑色;
fillRect定义了填充区域为矩形,并由四个参数来设置填充的位置及大小,第一二两个参数为相对canvas左上角的坐标值,三四两个参数为所填充的矩形区域的宽和高,填充颜色使用fillStyle值。与之相反的方法就是clearRect,用来擦除指定区域内容,参数及用法与fillRect类似。

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *