lib 发表于 2013-1-29 13:43:14

Canvas学习笔记(一)--基础知识

 
1、<canvas>元素
 
id:不是<canvas>元素专享,和标准的html标签一样,都可以为元素指定id;
width:元素宽度,默认为300px。可以通过dom和css进行设置;
height:元素高度,默认为150px。可以通过dom和css进行设置;
注:使用css设置width和height时,渲染图像会缩放适应布局,这意味着图像发生了变形,这时需要显示指定canvas的width和height属性的值。
 
canvas默认是全透明的,但是可以像图片一样指定样式(边距、边框、背景等),指定的样式不会对图像产生影响。
 
为了兼容旧版本浏览器,canvas提供了替换内容,例如:
 
<canvas id="stockGraph" width="150" height="150">current stock price: $3.15 +0.15</canvas><canvas id="clock" width="150" height="150"><img src="images/clock.png" width="150" height="150"/></canvas> 
 
2 、渲染上下文
 
 
canvas初始化是空白的,要在上面画图首先需要渲染上下文,
 
//通过id获取canvas元素对象var canvas = document.getElementById('canvas_test');//通过canvas获取上下文//注:2d是目前唯一的选择var context = canvas.getContext('2d');  
 3 、简单的例子
 

<!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><style type="text/css">.wraper {position: relative;border: 1px solid orange;}</style><script type="text/javascript">function draw(){var canvas = document.getElementById('test');if(canvas.getContext){var context = canvas.getContext('2d');context.fillStyle = "rgba(200,0,0,1)";context.fillRect(10,10,50,50);context.fillStyle = "rgba(0,0,200,0.3)";context.fillRect(30,30,70,70);}}</script></head>    <body ><canvas id="test" width="200px" height="200px" class="wraper"></canvas></body></html> 运行后的效果:
 
http://dl.iteye.com/upload/attachment/0064/5350/8d45bf4b-a631-33a6-9162-170e407144a7.png
 
页: [1]
查看完整版本: Canvas学习笔记(一)--基础知识