新的堆棧和編碼,試圖創建一個簡化的偵探遊戲(肯定已經咬過了我比較多的咀嚼,但我決定給它一個鏡頭)。如何讓這個HTML畫布動畫出現在我的圖像上?
這裏有一個codepen鏈接代碼:
http://codepen.io/anon/pen/ZbZREp
*************** HTML ************* ************
無
************** CSS ************** *************
body{
background:#000;
width: 100%;
height: 100%;
overflow:hidden;
}
*************** *************** * JS ****************************
var canvas = document.createElement('canvas');
var w = canvas.width = 800,
h = canvas.height = 600;
var c = canvas.getContext('2d');
var img = new Image();
img.src = 'http://oi41.tinypic.com/4i2aso.jpg';
var background = new Image();
background.src = "https://i2.wp.com/i2.listal.com/image/2669447/500full.jpg";
var position = {x : w/3.2, y : h/2.5};
document.body.appendChild(canvas);
var particles = [];
var random = function(min, max){
return Math.random()*(max-min)*min;
};
/*canvas.onmousemove = function(e){
position.x = e.offsetX;
position.y = e.offsetY;
};*/
function Particle(x, y){
this.x = x;
this.y = y;
this.velY = -2;
this.velX = (random(1, 10)-5)/10;
this.size = random(3, 5)/10;
this.alpha = 1;
this.update = function(){
c.drawImage(background,0,0);
this.y += this.velY;
this.x += this.velX;
this.velY *= 0.99;
if(this.alpha < 0)
this.alpha = 0;
c.globalAlpha = this.alpha;
c.save();
c.translate(this.x, this.y);
c.scale(this.size, this.size);
c.drawImage(img, -img.width/2, -img.height/2);
c.restore();
this.alpha *= 0.96;
this.size += 0.02;//
};
}
var draw = function(){
var p = new Particle(position.x, position.y);
particles.push(p);
while(particles.length > 500) particles.shift();
c.globalAlpha = 2;
c.drawImage(background,0,0);
c.fillRect(0,0,w,h);
for(var i = 0; i < particles.length; i++)
{
particles[i].update();
}
};
setInterval(draw, 1000/60);
在codepen上,如果你註釋掉JS部分的第35行,你會發現偵探的圖像背後有一個煙霧動畫(當然發現它在codepen上,並認爲它會製作一個很酷的吸菸動畫)。我能弄清楚如何將偵探圖像放入畫布中,但我無法弄清楚如何讓煙霧動畫出現在偵探形象的FRONT中。我已經嘗試了幾種方法,包括設置一個Javascript圖片onLoad,但所有的方法,這是最接近我可以達到我的預期目標。
我在這裏做錯了什麼?
非常感謝坊間,我就用這個來試試,並進一步剖析到我的項目 –