開心每一天1111
2023-02-24 16:04:01
我有一個圖片掉落的游戲 我將下一個函數 push() 到一個數組中,我的照片var bulletin在閃爍,所以我想這可能是我在使用 update() 函數時畫了很多function rect () { this.size = [rectSize.x, rectSize.y]; this.imagesSrc = rand(0, 1) ? 'bulletinYes' : 'bulletinNo'; this.position = [rand(0, w-rectSize.x), -rectSize.y]; this.bulletinValue = (this.imagesSrc === 'bulletinYes') ? 'bulletinYesValue' : 'bulletinNoValue';}rect.prototype = { draw: function (){ var bulletin = new Image(); bulletin.src = imagesSrc[this.imagesSrc]; ctx.drawImage(bulletin, this.position[0], this.position[2], this.size[0], this.size[2]); }}我試過var bulletin像這樣把功能放在外面var bulletin = new Image();bulletin.src = imagesSrc[this.imagesSrc]; <= ???function rect () { this.size = [rectSize.x, rectSize.y]; this.imagesSrc = rand(0, 1) ? 'bulletinYes' : 'bulletinNo'; this.position = [rand(0, w-rectSize.x), -rectSize.y]; this.bulletinValue = (this.imagesSrc === 'bulletinYes') ? 'bulletinYesValue' : 'bulletinNoValue';}rect.prototype = { draw: function (){ ctx.drawImage(bulletin, this.position[0], this.position[1], this.size[0], this.size[1]); }}但我不知道如何改變 [this..imagesSrc] 它才能工作。而且它只執行一次,并且圖片不會為每個推送的圖片隨機化。有沒有人有任何建議如何擺脫閃爍或改變bulletin.src = imagesSrc[this.imagesSrc];如果你想查看整個腳本,這是我的 github 鏈接我剛剛開始我的編碼路徑,所以感謝任何可以回答這個問題的人:)
1 回答

慕森王
TA貢獻1777條經驗 獲得超3個贊
您每次都創建新圖像并嘗試在加載圖像之前繪制它。更好的方法是在開始時準備所有圖像并繪制它。您的代碼稍作改動,一切都會起作用:
準備圖片:
var imagesSrc = {
ballotBoxImgSrc: 'img/ballotBox.png',
bulletinYes: 'img/yes.jpg',
bulletinNo: 'img/no.jpg'
};
var images = {
ballotBoxImgSrc: new Image(),
bulletinYes: new Image(),
bulletinNo: new Image()
}
for(let [name,value] of Object.entries(imagesSrc)) {
images[name].src = value;
}
畫:
rect.prototype = {
draw: function (){
var bulletin = images[this.imagesSrc];
ctx.drawImage(bulletin, this.position[0], this.position[1], this.size[0], this.size[1]);
}
}
添加回答
舉報
0/150
提交
取消