[英]JavaScript Image not drawing to canvas
我只是一個完整的菜鳥,一直在尋找答案。 “ctx.fillRect(0,0,100,100);” 表示ctx已正確聲明並且正在調用“ test()”的工作。 我只是不明白為什么這張圖不會畫出來。
var Img = new Image();
Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag
function test(){
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,100,100); //THIS WORKS
ctx.drawImage(Img,0,0,600,600); // Will not load
}
Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag
Img.scr未定義的屬性。 您應該嘗試使用Img.src
Img.src ='/client/Assets/StartScreen/Background.png';
兩件事情:
img.scr
,而不是img.src
。 img.complete
)。 您可以使用onload
事件偵聽器在圖像准備就緒后立即繪制內容。 var img = new Image();
img.src = "/client/Assets/StartScreen/Background.png";
function draw() {
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, 100, 100);
ctx.drawImage(img, 0, 0, 600, 600);
}
img.onload = function() {
draw();
};
僅應在加載圖像時將其添加到畫布。 嘗試,
var Img = new Image();
Img.src ='/client/Assets/StartScreen/Background.png';
Img.onload = function() {
test();
}
function test(){
ctx.fillStyle = 'blue';
ctx.fillRect(0,0,100,100);
ctx.drawImage(Img,0,0,600,600);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.