<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div id="box" style="width:600px;height:600px;margin:0 auto;border:2px solid #000;background:#000;"></div> <script type="text/javascript"> var canvasList = document.getElementById('box'); var canvas = document.createElement('canvas'); canvasList.appendChild(canvas); canvas.width = 600; // canvas.height = 600; var context=canvas.getContext("2d"); var width=600,height=600; var arr = []; for(var i=0;i<10;i++){ arr.push({x:parseInt(Math.random()*canvas.width),y:parseInt(Math.random()*canvas.height)}); }; var radius=10; //創建構造函數Circle function Circle(x,y,radius){ this.xx=x;//在畫布內隨機生成x值 this.yy=y; this.radius=radius; }; Circle.prototype.radiu=function(){ radius += 0.5; //每一幀半徑增加0.5 if (this.radius >= 20) { radius = 10; }; }; // 繪制圓形的方法 Circle.prototype.paint=function(){ context.beginPath(); context.arc(this.xx,this.yy,10,0,Math.PI*2); context.fillStyle="rgba(250,250,50,1)";//填充顏色,默認是黑色 context.fill();//畫實心圓 context.closePath(); context.lineWidth = 2; //線條寬度 context.strokeStyle = 'rgba(250,250,50,1)'; //顏色 context.stroke(); this.paintkong(); this.paintkong(0); this.paintkong(10); this.paintkong(20); }; Circle.prototype.paintkong=function(num){ context.beginPath(); context.arc(this.xx,this.yy,this.radius+num,0,Math.PI*2); context.closePath(); context.lineWidth = 1; //線條寬度 context.strokeStyle = 'rgba(250,250,50,1)'; //顏色 context.stroke(); }; // 創建 var newfun = null; function createCircles(){ for(var j=0;j<arr.length;j++){ newfun = new Circle(arr[j].x,arr[j].y,radius);//調用構造函數 newfun.paint(); }; newfun.radiu(); }; createCircles() // 創建臨時canvas var backCanvas = document.createElement('canvas'), backCtx = backCanvas.getContext('2d'); backCanvas.width = width; backCanvas.height = height; //設置主canvas的繪制透明度 context.globalAlpha = 0.7; //顯示即將繪制的圖像,忽略臨時canvas中已存在的圖像 backCtx.globalCompositeOperation = 'copy'; var render = function() { //先將主canvas的圖像緩存到臨時canvas中 backCtx.drawImage(canvas, 0, 0, width, height); //清除主canvas上的圖像 context.clearRect(0, 0, width, height); //在主canvas上畫新圓 createCircles(); //新圓畫完后,再把臨時canvas的圖像繪制回主canvas中 context.drawImage(backCanvas, 0, 0, width, height); }; setInterval("render()", 100); </script> </body> </html>

