代码改变世界

Canvas学习

2011-07-27 13:50  呦菜  阅读(336)  评论(0编辑  收藏  举报

 最近看过一些关于canvas的文章,由于以后的工作项目中会用到,便开始学习一下。

 <canvas>元素是HTML5标准的一部分。<canvas>只有两个属性,width和height,并且都是可选的。默认的宽为300px,高为150px。<canvas>元素必须有结束标签</canvas>.

 <canvas id="tutorial" width="150" height="150"></canvas>这样并没有对<canvas>只是简单的创建了一个canvas对象而已,这个时候的canvas元素和div没有区别,如果不设定样式的话再页面上是看不出来的。想要用javascript在上面画图首先需要渲染上下文,这可以通过canvas的对象getContext来实现,在传递的时候需要传递一个参数,目前唯一可以用的参数是2d.

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

以下为一个简单的<canvas>实例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");

ctx.fillStyle
= "rgb(200,0,0)";
ctx.fillRect (
10, 10, 55, 50);

ctx.fillStyle
= "rgba(0, 0, 200, 0.5)";
ctx.fillRect (
30, 30, 55, 50);
}
}
</script>
</head>

<body onload="draw()">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>

显示结果:

canvas只支持一种基本形状——矩形,所以其他图形都是由一个或多个路径组合而来。其中主要代码:

fillRect(x,y,width,height) : Draws a filled rectangle
strokeRect(x,y,width,height) : Draws a rectangular outline
clearRect(x,y,width,height) : Clears the specified area and makes it fully transparent

例子:

View Code
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");

ctx.fillRect(
25,25,100,100);
ctx.clearRect(
45,45,60,60);
ctx.strokeRect(
50,50,50,50);

}
}

显示结果:

fillRect 函数画了一个大的黑色矩形(100x100),clearRect 函数清空了中间 60x60 大小的方块,然后strokeRect 函数又在清空了的空间内勾勒出一个 50x50 的矩形边框。