前段时间复习HTML5标签时看见<canvas>这个标签,在网上搜了一下发现是一图形容器类似画板。
做了一些简单的案例;
1,在canvas画布上通过上下左右控制方块移动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上下左右</title> </head> <body> <canvas id="can2" width="800" height="600" style="background-color:#ffff00"></canvas> </body> <script> var my = document.getElementById('can2'); var go = my.getContext('2d'); document.onkeydown=jumpPage; var canY = 0,canX = 0; go.fillStyle = '#f0f'; go.fillRect(0, 0, 50, 50); function jumpPage() { go.clearRect(0,0,800,600); if (event.keyCode==37)//左 canX-=10; if (event.keyCode==38)//上 canY-=10; if (event.keyCode==39)//右 canX+=10; if (event.keyCode==40)//下 canY+=10; if(canX>750 ){ canX=750; }else if(canX<0){ canX=0; } if(canY<0 ){ canY=0; }else if(canY>550){ canY=550; } go.fillRect(canX, canY, 50, 50); } </script> </html>
2,在canvas画布上点击产生圆
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas点击显示随机大小圆</title> </head> <body> <canvas id="can2" width="800" height="600" style="background-color:#ffff00"></canvas> </body> <script> var my = document.getElementById('can2'); var go = my.getContext('2d'); var num= 0; go.fillStyle = '#0a0'; my.onclick=function(ev){ var oEvent=ev||event; var oLeft=oEvent.clientX - my.offsetLeft + 'px'; var oTop=oEvent.clientY - my.offsetTop + 'px' go.beginPath(); var canR = parseInt(30*Math.random()+10); go.arc(parseInt(oLeft),parseInt(oTop),canR,0,2*Math.PI) go.fill() } </script> </html>
3,下雨效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>下雨效果</title> </head> <body> <canvas id="can2" width="1900" height="600" style="background-color:#ffffff"></canvas> </body> <script> var my = document.getElementById('can2'); var go = my.getContext('2d'); var ary = []; setInterval(function(){ var e = e || event ; var oLeft= parseInt(1900*Math.random()) ; var oTop= -50; var canh = parseInt(50*Math.random()+10); var rgb = parseInt(255*Math.random()); var lw = parseInt(5*Math.random()); var my_obj = { x:oLeft, y:oTop, h:canh, w:lw, fun:function(){ go.beginPath(); go.lineWidth=my_obj.w; go.beginPath(); go.moveTo(my_obj.x , my_obj.y); go.lineTo(my_obj.x , my_obj.y + my_obj.h); go.stroke(); } }; ary.push(my_obj); var set = setInterval(function(){ my_obj.y+=10; if(my_obj.y>=600){ clearInterval(set); ary.shift(my_obj) } },10); },25); function draw(){ go.clearRect(0,0,1900,600); ary.forEach(function(obj){ obj.fun(); }); requestAnimationFrame(draw); } draw(); </script> </html>
出道那么久,我赚了两个忆,一个失忆,一个回忆。