我尝试使用javascript创建动态画布动画。目的是增加许多图像对象的x属性,然后每次运行draw()函数时在更新的x属性的x位置绘制它们。我虽然无法成功递增此x属性 - 由于某种原因它总是重置为0.
我将此全局数组定义为包含我将绘制的所有对象:
overflow:hidden;
我有这个对象构造函数来创建新的图像对象:
window.character = [];
在构造函数内部,有一些奇怪的行为。我使用以下方法创建了一个新对象:
function Character(name, x, y){
//define the image object within the Character
this.imageObject = new Image();
this.imageObject.src = name+'iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAW0lEQVR42mL8//8/AzpgZGTcC6KBcs5wMRwK/0MVMsLEmLAoEmXAApiwiKUhaRJCltgLsQVsWwIQ/wTx0fBeRigD7B6Y24i1mj4Kn4KI7Uie2Y7FI8+B2AMgwABjRynfWgpcxQAAAABJRU5ErkJggg==';
window.character.push(this);
window.characterPosition = window.character.indexOf(this);
//set natural width and natural height once the image is loaded
if (this.imageObject.addEventListener){
this.imageObject.addEventListener('load', function(){
window.imgWidth = this.naturalWidth/2;
window.imgHeight = this.naturalHeight/2;
//set natural width and natural height to object
window.character[characterPosition]['imageObject']['w'] = window.character[characterPosition]['imageObject']['w0'] = window.imgWidth;
window.character[characterPosition]['imageObject']['h'] = window.character[characterPosition]['imageObject']['h0'] = window.imgHeight;
//set initial x and y position
console.log(x);
window.character[characterPosition]['imageObject']['x'] = x;
window.character[characterPosition]['imageObject']['y'] = y;
console.log(window.character[characterPosition]['imageObject']['x']);
//set loaded property for the object once loading is done
window.character[characterPosition]['imageObject']['loaded'] = true;
function imageLoaded(element, index, array){
return element['imageObject']['loaded'] == true;
}
//test whether every object in array has the image loaded
if(character.every(imageLoaded)){
$('button#play').show();
};
});
} //end object constructor
然后,这是我从对象构造函数中的console.log消息中看到的内容:
var sun0 = new Character('data:text/javascript;base64,', 12, 12);
最终,我想知道如何在屏幕上为对象设置动画。这个draw()函数每10ms运行一次。
console.log(x); //returns 12, as expected
window.character[characterPosition]['imageObject']['x'] = x;
window.character[characterPosition]['imageObject']['y'] = y;
console.log(window.character[characterPosition]['imageObject']['x']); //returns 0. Thought it would be 12
我怎样才能得到这个' x'要增加的财产?
答案 0 :(得分:3)
Pointy在评论中回答了您的问题,但要扩展此问题......您正尝试在无法设置的x
上设置Image
。例如,在浏览器的控制台中尝试:
var img = new Image();
img.x = 1;
console.log(img.x); // this will be zero
这实际上就是你正在做的事情。此外,在您的代码中尝试将['x']
更改为['myX']
,然后它将按预期工作。