qq_请叫我小仙女
2017-01-28 19:12
var WINDOW_WIDTH;
var WINDOW_HEIGHT;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var deltaTime;
var lastTime;
var starPic = new Image();
var stars = [];
var num = 30;
var starObj=function(){
this.x;
this.y;
this.timer;
this.picNo;
}
starObj.prototype.init=function(){
this.x=Math.random()*canvas.width;
this.y=Math.random()*canvas.height;
this.picNo=Math.floor(Math.random()*7);
this.timer=0;
}
starObj.prototype.update=function(){
this.timer+=deltaTime;
if(this.timer>30){
this.picNo+=1;
this.picNo%=7;
}
}
starObj.prototype.draw=function(){
context.drawImage(starPic,this.picNo*7,0,7,7,this.x,this.y,7,7);
}
window.onload=function() {
WINDOW_WIDTH = document.body.scrollWidth || document.documentElement.scrollWidth;
WINDOW_HEIGHT = document.body.scrollHeight || document.documentElement.scrollHeight;
canvas.width = WINDOW_WIDTH;
canvas.height = WINDOW_HEIGHT;
context.fillStyle='black';
context.fillRect(0,0,canvas.width,canvas.height);
starPic.src='image/star.png';
for(var i=0;i<num;i++){
var obj=new starObj();
stars.push(obj);
stars[i].init();
}
lastTime=Date.now();
gameLoop();
}
function gameLoop(){
window.requestAnimationFrame(gameLoop);
var now=Date.now();
deltaTime=now-lastTime;
lastTime=now;
drawStars();
}
function drawStars(){
for(var i=0;i<num;i++){
stars[i].update();
stars[i].draw();
}
}
if(this.timer > 30){
this.picNo +=1;
this.picNo %=7;
this.timer = 0;
}
canvas实现星星闪烁特效
54187 学习 · 121 问题
相似问题