如何让这个HTML画布动画显示在我的图像上?

时间:2015-11-22 02:50:48

标签: javascript jquery html css canvas

堆叠和编码的新手,尝试创建一个简化的侦探游戏(绝对比我可以咀嚼更多的咬,但我决定试一试)。

这是代码的codepen链接:

http://codepen.io/anon/pen/ZbZREp

*************** HTML *************************

************** CSS ***************************

<controls:Tile Title="Hello!" 
   TiltFactor="2"
   Width="100" Height="100" 
   Count="1">
</controls:Tile>

**************** JS ****************************

body{
  background:#000;
  width: 100%;
  height: 100%;
  overflow:hidden;
}

在codepen上,如果你在JS部分注释掉第35行,你会看到侦探的图像后面有一个烟雾动画(当然在codepen上找到它并认为它会产生一个很酷的吸烟动画)。我能够弄清楚如何将侦探图像放入画布中,但我无法弄清楚如何让烟雾动画出现在侦探图像的FRONT中。我已经尝试了几种方法,包括在onLoad上设置Javascript图片,但是在所有方法中,这是我能达到预期目标的最接近的方法。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

在绘制粒子之前绘制背景图像:

&#13;
&#13;
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);

  // draw the background image before you draw the particles
  c.drawImage(background,0,0);

  while(particles.length > 500) particles.shift();

  for(var i = 0; i < particles.length; i++)
  {
    particles[i].update();
  }

};

setInterval(draw, 1000/60);
&#13;
body{ background-color: black; }
canvas{border:1px solid red; }
&#13;
&#13;
&#13;

相关问题