簡體   English   中英

Javascript-使用ctx.drawImage在對象數組中顯示圖像

[英]javascript - Using ctx.drawImage to show image inside an array of objects

它沒有顯示圖像,我以各種可能的方式嘗試了,但我不知道怎么做。 我應該怎么做:

1)如何創建一個新的對象object('20','X',250,100,'img'); 並指定我要使用的圖片? img.player或img.player.src還是img? 2)如何遍歷顯示在畫布上的所有對象數組?

 15index.html: 38 Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)' 

 <!DOCTYPE html> <html lang="en"> <head> <title></title> </head> <body> <canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas> <script> var WIDTH = 500; var HEIGHT = 500; var ctx = document.getElementById("ctx").getContext("2d"); ctx.font = '30px Arial'; var img = {}; img.player = new Image(); img.player.src = "FireMonster.png" var objectArray = {}; function object(id, name, x, y, img) { var object3 = { x: x, y: y, name: name, id: id, img: img, }; objectArray[id] = object3; } object('20', 'X', 250, 100, 'img'); object('21', 'P', 150, 150, 'img'); drawingObject = function(something) { ctx.drawImage(something.img, something.x, something.y); } update = function() { for (var x in objectArray) { drawingObject(objectArray[x]); } } setInterval(update, 40); </script> </body> </html> 

您正在將'img'的文本傳遞給object function而不是Image對象。 嘗試以下方法:

object('20', 'X', 250, 100, img.player);
object('21', 'P', 150, 150, img.player);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM