使用javascript构造函数设置画布动画
大家好,我的社区! 首先,我必须说,我没有太多的经验与建设者。 所以我想做的是给一个伞兵制作动画,让他从屏幕的顶部飞到底部。 我想我可以用一个构造器来设置一个伞兵:使用javascript构造函数设置画布动画,javascript,animation,canvas,constructor,runtime-error,Javascript,Animation,Canvas,Constructor,Runtime Error,大家好,我的社区! 首先,我必须说,我没有太多的经验与建设者。 所以我想做的是给一个伞兵制作动画,让他从屏幕的顶部飞到底部。 我想我可以用一个构造器来设置一个伞兵: var parachute = function() { this.height = 35; this.width = 30; this.speed = 50; this.xPos = Math.round(Math.random() * (window.width - this.width));
var parachute = function() {
this.height = 35;
this.width = 30;
this.speed = 50;
this.xPos = Math.round(Math.random() * (window.width - this.width));
this.animate = function() {
this.img = new Image();
this.yPos = 0;
this.img.onload = function() {
ctxPara.globalCompositeOperation = 'copy';
ctxPara.translate(0, this.yPos);
ctxPara.drawImage(this.img, this.xPos, 0);
};
this.img.src = 'para.png';
this.yPos++;
};
})
此构造函数用于名为“fly”的函数:
var fly = function() {
var newParachute = new parachute();
setInterval(newParachute.animate, newParachute.speed);
};
该“飞行”功能在窗口加载时触发:
window.onload = function() {
var canvasBg = document.getElementById('canvasBg');
// I splitt the Background and the parachutists in two canvas elements
// handling the problem (to erase content and draw new content) with
// the canvas animation.
var canvasPara = document.getElementById('canvasPara');
ctxPara = canvasPara.getContext('2d');
canvasPara.width = window.width;
canvasPara.height = window.height;
canvasBg.width = window.width;
canvasBg.height = window.height;
fly();
clouds(); // background is loading here
};
你应该看到的是一个伞兵从屏幕上飞下来。但不幸的是你没有。。。
现在,在那篇长课文之后。(我很抱歉这么长:-()我的问题是:你知道我做错了什么吗?我的老师是对的吗?我想做的是这样写的吗?对成功的机会有什么建议吗?(我希望我的英语没有我想的那么糟糕:-)
哦,我忘了提到错误了。这是一个类型错误。
这意味着“this.img”不是此行的img元素:
ctxPara.drawImage(this.img, this.xPos, 0);
现在,我以markE为例。
而不是给我看一个伞兵。它显示了这行中的一个错误:ctxPara.drawImage(this.img,this.xPos,this.yPos)
我又卡住了。但现在我甚至不知道原因。。。请帮忙 演示:
有几个问题:
(1) 要获取窗口宽度,可以使用:
window.innerWidth
(2) setInterval调用newcampile.animate
setInterval(newParachute.animate, newParachute.speed);
但是这个
在内部设置窗口对象的动画,而不是降落伞对象
要提供正确的this
动画,您可以使用调用
方法,如下所示:
var newParachute = new parachute();
setInterval(function(){newParachute.animate.call(newParachute);}, newParachute.speed);
(3) 您需要清除以前绘制的图像,否则它们仍将显示在画布上。非常感谢!to(3):我使用以下代码行处理此问题:ctxPara.globalCompositeOperation='copy';
var newParachute = new parachute();
setInterval(function(){newParachute.animate.call(newParachute);}, newParachute.speed);