简体   繁体   中英

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

I looked at a bunch of other questions on how to add Images to a canvas object in Javascript and I can't seem to get it to work for me. What I have is an array of objects which hold the location and dimension of a bunch of tiles, this is so I can reference the tiles latter, which makes it very complicated to apply and my code is a bit of a mess from me trying to fix it. Here is the full code.

 <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> 

I looked at a bunch of other questions and it seems the problem is loading the image before adding it to the canvas. I can't work out how to implement it in this case.

通过将prinTile中的图像从var更改为this来进行修复。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM