Canvas是HTML5的新生元素,它允许用户在上面任何2d图形,也能添加图片,3D画图暂时还没有具体的标准。canvas最基础的是如何画线,包括线条的宽度、颜色、拐角类型、常用函数曲线等等。canvas本身没有作图功能,必须借助javascript来绘图。下面结合javascript做一个实例,供大家学习canvas之用。
实例分为两个部分:随机画线和小方块反弹运动。
点击下方按钮,查看演示效果:
第一步、html代码只需要建立一块画布canvas和添加两个启动按钮
<!DOCTYPE html> <html> <head> <title>HTML5 Canvas Randomness</title> </head> <body> <section id="content"> <canvas height='400' id='canvas' width='600'></canvas> <br /> <button onClick="scribble()" class="scribble"><b>随机画画</b></button> <button onClick="motion()" class="scribble" ><b>方块运动</b></button> </section> </body> </html>第二步、添加一个脚本用来控制画布
javascript代码:
<script type='text/javascript'> var icount = 0; var myInterval; function scribble() { canvas = document.getElementById('canvas'); if (canvas.getContext){ ctx = canvas.getContext('2d'); clearInterval(myInterval); ctx.clearRect (0, 0, canvas.width, canvas.height); this.gridSize = 1; ctx.globalAlpha = 0; myInterval = setInterval(makeScribble,80); } } function makeScribble(){ var cw = canvas.width; var ch = canvas.height; icount+=1 if(icount>10){ctx.clearRect (0, 0, cw, ch); icount=0;ctx.beginPath();ctx.globalAlpha = 0;} ctx.globalAlpha +=0.01; ctx.beginPath(); ctx.moveTo(retRandom(cw),retRandom(ch)); ctx.strokeStyle = random_color(); ctx.lineWidth = retRandom(10); for (var x = 0; x <= retRandom(50); x++) { if(retRandom(10)>5) { ctx.quadraticCurveTo(retRandom(cw),retRandom(ch), retRandom(500),retRandom(90)); } //arc(x, y, radius, startAngle, endAngle, anticlockwise) else {ctx.lineTo(retRandom(cw),retRandom(ch));} ctx.stroke(); } } var iCountHeight=2; var iCountWidth=2; var x=0; var y=0; function motion() { canvas = document.getElementById('canvas'); if (canvas.getContext){ ctx = canvas.getContext('2d'); //x=0; //y=0; clearInterval(myInterval); ctx.globalAlpha = 1; ctx.clearRect (0, 0, canvas.width, canvas.height); myInterval = setInterval(makemotion,10); } } function makemotion(){ var cw = canvas.width; var ch = canvas.height; ctx.clearRect (0, 0, cw, ch) icount+=1 if (iCountHeight+y+20>ch || iCountHeight+y<0 ){iCountHeight =- iCountHeight} if (iCountWidth+x+20>cw || iCountWidth+x<0){iCountWidth =- iCountWidth} ctx.fillStyle = "#000"; x += iCountWidth; y += iCountHeight; ctx.fillRect(x,y, 20, 20); } function random_color() { var rint = Math.round(0xffffff * Math.random()); return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')'; } function retRandom(upper){ return Math.floor(Math.random()*upper); } function retRandomTF(){ if(retRandom(10) > 5){return true} else {return false;}; } </script>本文有HTML5Party编辑整理,转载请注明出处!