我正在为我们的内部应用程序构建一个奇特的 easteregg。因此,我有一个图像“骑”过屏幕。为了增强花哨性,我想向图形后面的车辆添加烟雾。
对于烟雾,我实现了这支笔的修改版本: http://codepen.io/CucuIonel/pen/hFJlr
结果如下: http://jsfiddle.net/vc2d08bt/4/
重要的代码片段(我猜)可以在 fiddle 中找到,搜索:
setInterval(function () {
position.x = $('#crystalship_exhaust').offset().left;
position.y = $('#crystalship_exhaust').offset().top;
}, 100);
由于笔将烟雾绑定(bind)到光标偏移,我尝试将其绑定(bind)到车辆“内部”的跨度,以跟随。但是烟雾在两个 X 方向上都在增长,甚至没有靠近车辆。
我在这里做错了什么?我对 Canvas 不是很熟悉,但感谢您的帮助。
提前致谢!
最佳答案
我已将运动添加到排气装置冒烟的汽车上。鼠标在屏幕上移动,但如果您愿意,这很容易改变。我将分音的情感方向更改为 Y 而不是 X,因此它向后移动并移动带有发射器的汽车图像。
http://codepen.io/anon/pen/JYapqr
Javascript:
var canvas = document.createElement('canvas');
var w = canvas.width = 1200,
h = canvas.height = 700;
var c = canvas.getContext('2d');
var img = new Image();
//添加了一个新的汽车图片
var car = new Image();
img.src = 'http://oi41.tinypic.com/4i2aso.jpg';
//并设置它的src属性
car.src = 'https://openmerchantaccount.com/img2/crystalship.png';
//将起始位置设置为 -car length 这样它就不会只出现在屏幕上
var position = {x : -250, y : h/2};
document.body.appendChild(canvas);
var particles = [];
var random = function(min, max){
return Math.random()*(max-min)*min;
};
function Particle(x, y){
this.x = x;
this.y = y;
//将偏音的方向改为向右,而不是向上。
this.velX = -2;
this.velY = (random(1, 10)-5)/10;
this.size = random(3, 5)/10;
this.alpha = 1;
this.update = function(){
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(){
//要动画移动,绘制时将位置向右移动 2px
position.x+=2;
position.y;
//如果小车到达终点我就把它移回起点
if(position.x+250>w){
position.x=-250;
}
var p = new Particle(position.x, position.y);
particles.push(p);
while(particles.length > 500) particles.shift();
c.globalAlpha = 1;
c.fillStyle = '#000';
c.fillRect(0,0,w,h);
//将图像绘制回屏幕
c.drawImage(car, position.x,position.y-80,250,100);
for(var i = 0; i < particles.length; i++)
{
particles[i].update();
}
};
setInterval(draw, 1000/60);
关于javascript - Canvas 烟雾颗粒不动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33548192/