<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <head> <script type="text/javascript" src="assets/js/jquery-2.0.3.min.js"></script> <script type="text/javascript"> function draw() { var Sprite = function(){ this.speed={ x:1, y:1, type:true }; }; Sprite.prototype={ draw:function(){ }, move:function(){//移動 this.y+=this.speed.y; this.x+=Math.random()*0.2; if(this.childs!=null&&this.childs.length>0){ for(var i = 0;i<this.childs.length;i++){ this.childs[i].speed = this.speed; this.childs[i].move(); } } }, appendChild:function(sprite){ if(this.childs == null)this.childs=[]; this.childs.push(sprite); }, drawChild:function(Sprite){ if(this.childs != null && this.childs.length > 0){ for(var i = 0; i<this.childs.length;i++){ this.childs[i].draw(); } } } }; var Canvas = function(){ this.interval = null; this.sprites = []; }; Canvas.prototype = { begin:function(){ this.interval = setInterval((function(param){ return function(){param.render();}; })(this),20); }, render:function(){ this.ctx.clearRect(-800,-800,1600,1600); this.ctx.fillStyle="#1E90FF"; this.ctx.fillRect(0,0,800,800); for(var i in this.sprites){ if(typeof(this.sprites[i]) == 'function'){ continue; } /* this.sprites[i].x = Math.random()*800; this.sprites[i].y = Math.random()*800; */ //this.sprites[i].radius-=0.005; //this.sprites[i].config.strokeStyle = "rgba("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+",0.8)"; this.sprites[i].draw(); } }, addSprite:function(name,sprite){ this.sprites[name] = sprite; }, stop:function(){ clearInterval(this.interval); }, clear:function(){ for(var i in this.sprites){ if(typeof(this.sprites[i]) == 'function'){ continue; } if(this.sprites[i].x>800&& this.sprites[i].y>800){ delete this.Sprites[i]; } } } }; var Koch = function(ctx, x, y, img,width){ this.ctx = ctx; this.x = x; this.y = y; this.width = width; this.img = img; }; Koch.prototype = new Sprite(); Koch.prototype.draw = function(){ this.ctx.drawImage(this.img,this.x,this.y,this.width,this.width); }; var ctx = document.getElementById("canvas").getContext("2d"); var can = new Canvas(); ctx.strokeStyle = "#f0f"; ctx.fillStyle="#1E90FF"; ctx.fillRect(0,0,800,800); can.ctx = ctx; can.begin(); setInterval(function(){ for(var i in can.sprites){ if(typeof(can.sprites[i]) == 'function'){ continue; } can.sprites[i].move(); } },20); var img = new Image(); index = 0; img.src="image/koch.png";//雪花縮略圖 setInterval(function(param){ for(var i = 0;i<Math.random()*50;i++){ var koch = new Koch(ctx, Math.random()*800,Math.random(),img,20); koch.speed = {x:0,y:Math.random()+0.5}; can.addSprite(index,koch); index++; } },500); } </script> </head> <body onload="draw();"> <canvas id="canvas" width="800" height="800" style="border: 1px solid red;"></canvas> </body> </html>