首页 > 下载 > 下载详文:Html5 canvas 标签

Html5 canvas 标签

发布时间:2011年02月03日 19时46分58秒   属性:程序Web开发 > Javascript/Html    访问次数:77519
字体: 初始 添加收藏 分享给好友
Html5 canvas 标签

Hrml5 canvas标签是Html5 开发的一个重要部分,canvas标签是Html5 javascript 脚本编写动态呈现的结果,可以说就是Html5的一个画布,通过canvas标签绘制二维图形、动画或者三维绘图,本文实展示Html5 canvas绘制二维图形。

示例一 绘制四边形矩形和圆形

在canvas中绘制四边矩形和圆形,先通过 document.getElementById("canvas") 获取canvas的id,然后指定canvas.getContext("2d");属性fillStyle为填充样式即填充颜色,fillRect为矩形建立,fillRect方法四个参数fillRect(x,y,widht,height)即x坐标、y坐标、宽和高的参数设定;arc绘制圆弧形,绘制arc需要带入圆周率Math.PI * 2,strokeStyle为边框色设定和stroke()配合使用。

HTML 代码  复制
<script type="application/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, 50, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect(30, 30, 55, 50); //绘制圆 ctx.strokeStyle = "#766666"; ctx.fillStyle = "green"; ctx.beginPath(); ctx.arc(100, 100, 50, 0, Math.PI * 2, true); ctx.closePath(); ctx.stroke(); ctx.fill(); } <script> <body style="" onload="draw();"> <canvas id="canvas" width="160" height="160" style="position:absolute; border:1px solid black; background-color:transparent"> <canvas> <body>

(图为上面代码绘制效果)

示例二 动画

在canvas中绘制矩形和三角形以及文字并且实现动画,rotate属性为旋转,ranslate为移动,在示例中设置了setInterval(draw, 30)定时触发drew()方法,定义了degrees、degrees01、degrees03,前两个是矩形和三角形rotate属性接收,degrees为递增也就让矩形顺时针方向旋转,degrees01为三角行形的rotate接收,degrees03为递减即让三角形逆方向旋转; fillText文字填充,font属性为文字样式定义, degrees03为文字判断条件,当degrees03值为10至20时文字显示为白色,小于10时为红色,同时为20时degrees03为-20递增。

HTML 代码  复制
<script type="text/javascript"> setInterval(draw, 30); var degrees = 0; var degrees01 = 0; var degrees02 = 0; function draw() { var canvas = document.getElementById('canvas'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); //矩形 ctx.clearRect(0, 0, 150, 150); degrees += 0.016; ctx.save(); ctx.translate(75, 75); ctx.rotate(degrees); ctx.fillStyle = "rgb(200, 0, 0)"; ctx.fillRect(-25, -25, 50, 50); ctx.restore(); degrees01 -=0.02; ctx.save(); //三角形 ctx.fillStyle = "green"; ctx.beginPath(); ctx.translate(75, 75); ctx.rotate(degrees01); ctx.moveTo(20, 45); ctx.lineTo(10, 65); ctx.lineTo(30, 65); ctx.fill(); ctx.restore(); //文字 ctx.font = "12px sans-serif"; ctx.fillText("www.weisim3.com", 100, 195); degrees02 += 1; if (degrees02 >= 10 && degrees02 <= 20) { ctx.fillStyle = "#FFFFFF"; if (degrees02 == 20 ){ degrees02 = -20; } } else { ctx.fillStyle = "red"; } } } <script> <body onload="draw();"> <canvas id="canvas" width="200" height="200" style="border:1px solid black"> <canvas> <body>

(示例二的动画效果)

免费
Html5 canvas 标签 (11)
本下载连接不支持第三下载工具打开,请直接点击下载即可
文章版权归属weisim3.com所有,未经书面版权许可同意,不得私自转载(或做修改转载),源文件示例仅供学习使用,更不要出于商业用途或印刷出版发行!否则将追究其相关法律责任,版权联系QQ:729260499。
遺昕 | Weisim3.com 下载许可条款 ( 您必须接受同意才可下载 ) .