我无法在Javascript

时间:2018-02-21 13:50:43

标签: javascript html5 html5-canvas

我查看了一些关于如何在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>
&#13;
&#13;
&#13;

我查看了一堆其他问题,似乎问题是在将图像添加到画布之前加载图像。在这种情况下,我无法解决如何实现它。

1 个答案:

答案 0 :(得分:0)

通过将prinTile中的图像从var更改为此来管理以修复它。