效果图:
代码:
一点点来先来个简单的
window.onload = function() { // body... var oC = document.getElementById('c1'); var oGc = oC.getContext('2d'); var iNow = 0; oGc.strokeRect(0,0,100,100); setInterval(function(){ iNow++; oGc.clearRect(0,0,oC.width,oC.height);//画布清空 oGc.strokeRect(iNow,iNow,100,100); },30)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body { background: black; } canvas { background: white; } </style> <script> window.onload = function() { // body... var oC = document.getElementById('c1'); var oGc = oC.getContext('2d'); var strArr = []; //新版本定时器的效果比 setInterval 更好 window.requestAnimationFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) { window.setTimeout(callback, 1000 / 60); //为什么要1000/60 一秒钟走60帧 } })() function show() { requestAnimationFrame(show); oGc.clearRect(0, 0, oC.width, oC.height); //画布清空 for(var i = 0; i < strArr.length; i++) { //如何加重力 strArr[i].sY += 0.02; //变化位置 strArr[i].x += strArr[i].sX; strArr[i].y += strArr[i].sY; //底边零界点 if(strArr[i].y >= oC.height - strArr[i].r) { strArr[i].y == oC.height - strArr[i].r //如何让其反弹 是摩擦系数 strArr[i].sY *= -1; strArr[i].sY *= 0.9; strArr[i].sX *= 0.9; } //侧边的零界点 if(strArr[i].x <= strArr[i].r) { strArr[i].x == 0; strArr[i].sX *= -1; strArr[i].sX *= 0.9; strArr[i].sY *= 0.9; } if(strArr[i].x > oC.width - strArr[i].r) { strArr[i].x == oC.width - strArr[i].r; strArr[i].sX *= -1; strArr[i].sX *= 0.9; strArr[i].sY *= 0.9; } if(Math.abs(strArr[i].sX) <= 0.09) { //删除无用元素 strArr.splice(i, 1); } } for(var i = 0; i < strArr.length; i++) { oGc.beginPath() oGc.fillStyle = 'rgba(' + strArr[i].c1 + ',' + strArr[i].c2 + ',' + strArr[i].c3 + ',' + strArr[i].c4 + ')'; oGc.moveTo(strArr[i].x, strArr[i].y) oGc.arc(strArr[i].x, strArr[i].y, strArr[i].r, 0, 360 * Math.PI / 180, false); //第四个参数弧度 顺时针false oGc.closePath(); oGc.fill(); }; //如何保证定时器的性能 requestAnimationFrame 防止堵塞 作用运动频率保持在60 } show(); setInterval(function() { //居中 var x = oC.width / 2; var y = oC.height - 20; var r = 10; //添加颜色 rgba var c1 = Math.floor(Math.random() * 255); var c2 = Math.floor(Math.random() * 255); var c3 = Math.floor(Math.random() * 255); var c4 = 1; //透明度 //var sX = -2;//写死的值 var sX = Math.random() * 6 - 3; //-3 到 3的值 var sY = -(Math.random() * 3 + 1); // 1 到 4之间 strArr.push({ x: x, y: y, r: r, c1: c1, c2: c2, c3: c3, c4: c4, sX: sX, sY: sY }) }, 300) } </script> </head> <body> <canvas id="c1" width="1200" height='500'></canvas> </body> </html>
技巧: