我有一個bird = {}對象,我在其中定義繪圖函數,但在渲染函數中調用時不會顯示圖像。任何人都可以指出我做錯了什麼?提前致謝。JS圖像未顯示在畫布上
編輯:我已經注意到它並不總是出現的原因是因爲屏幕上還有其他精靈,當我將它們關閉時,鳥總是出現。有什麼可以解決這個問題嗎?
bird = {
draw:function() {
var birdimg = new Image();
birdimg.onload = function() {
ctx.drawImage(birdimg, -20, height - 200);
}
birdimg.src = "//i.stack.imgur.com/nsZLM.png"; //"assets/bird.png";
}
};
function main() {
canvas = document.createElement("canvas");
//Set the width and height to the sizes of the browser
width = window.innerWidth;
height = window.innerHeight;
//Frames the game if the width is larger than 500
if(width >=500){
width = 320;
height = 480;
canvas.style.border = "1px solid #000";
evt = "mousedown";
}
//Sets the canvas sizes to the width and height variables
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
//Set the default state
currentstate = states.Splash;
document.body.appendChild(canvas);
render();
}
function render(){
//Adding bird
bird.draw();
//Loads sky.png
bgimg = new Image();
bgimg.onload = function() {
ctx.drawImage(bgimg,-20,height-200);
ctx.drawImage(bgimg,256,height-200);
}
bgimg.src = "assets/sky.png";
//Loads land img
landimg = new Image();
landimg.onload = function() {
ctx.drawImage(landimg,0,height-100);
}
landimg.src = "assets/land.png";
//Creates rectangle that colors background. THIS IS THE BOTTOM LAYER. WRITE CODE ABOVE
ctx.fillStyle="#4ec0ca";
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.stroke();
}
的main()不會被調用? 「狀態」不存在,資產只存在於本地計算機上(您需要上傳)。還要考慮使用變量來存儲值。 – K3N
我沒有寫在這裏,但它是在原來的代碼。關於原來的問題,你有什麼好意思的建議嗎? – UpARiver
您可以上傳鳥圖像(使用編輯器中的圖片上傳按鈕),並將img src鏈接到該圖片上,以便我們檢查鳥是否繪製在畫布區域之外。同時還要減少包含在問題中的例子,以便它可以運行(不使用'states',或者至少使用定義的狀態,調用main()等)。 – K3N