簡體   English   中英

我無法使用Javascript將圖像添加到畫布

[英]I can't add an Image to a canvas in Javascript

我看了其他有關如何在Javascript中將圖像添加到畫布對象的問題,但似乎無法使它正常工作。 我所擁有的是一組對象,這些對象保存着一堆瓷磚的位置和尺寸,因此我可以稍后引用這些瓷磚,這使得應用非常復雜,並且我的代碼對我來說有點混亂修理它。 這是完整的代碼。

 <script> var boardHieght = 6; var boardLength = 15; var board = new Array(boardLength); var empty="BlankSquare.bmp"; for (i = 0; i < boardHieght; i++) { board[i] = new Array(boardLength); } function createBoard() { createArray(); myGameArea.start(); } var myGameArea = { canvas : document.createElement("canvas"), start : function() { this.canvas.width = 1000; this.canvas.height = 500; this.context = this.canvas.getContext("2d"); document.body.insertBefore(this.canvas, document.body.childNodes[0]); this.interval = setInterval(updateGameArea, 20); } } function createArray(){ for(i=0; i<boardHieght; i++){ for(j=0; j<boardLength; j++){ board[i][j]= new tile(50*i, 50*j, 50, 50 , "BlankSquare.bmp"); } } } function tile(x, y, height, length, contents){ this.x=x; this.y=y; this.height=height; this.length=length; this.contents=contents; } function buildBoard(){ for(i=0; i<boardHieght; i++){ for(j=0; j<boardLength; j++){ var x=board[i][j].x; var y=board[i][j].y; var height=board[i][j].height; var length=board[i][j].length; var contents=board[i][j].contents; var curretnTile= new printTile(x, y, height, length, contents); curretnTile.update(); } } } function printTile(x, y, height, length, cnt){ this.cnt=cnt; this.x=x; this.y=y; this.height=height; this.length=length; var image = new Image(); image.src=cnt this.update = function() { ctx=myGameArea.context; ctx.drawImage(image, this.x, this.y, this.length, this.height); } } function updateGameArea(){ buildBoard(); } </script> 

我看了一堆其他問題,看來問題是在將圖像添加到畫布之前先加載圖像。 在這種情況下,我無法解決如何實現它。

通過將prinTile中的圖像從var更改為this來進行修復。

暫無
暫無

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

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