六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 134|回复: 0

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

[复制链接]

升级  25.33%

24

主题

24

主题

24

主题

秀才

Rank: 2

积分
88
 楼主| 发表于 2013-1-24 06:37:16 | 显示全部楼层 |阅读模式
 
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> 运行后的效果:
 

 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表