为什么JavaScript不能在画布上绘制图像?

4

我在绘制画布时遇到了问题。没有错误,但是仍然没有绘制图像。请查看代码块,看看是否能发现我无法发现的问题:

function loadPacman(posX, posY) {
    this.posX = posX;
    this.posY = posY;
    pacman = new Image();
    pacman.src="http://www.frogbug.se/pacman/img/naziman.png";
    pacman.addEventListener("load", function(){
            canvas.drawImage(pacman, this.posX, this.posY)
        }, false);
}

function loadGhost(posX, posY) {
    this.posX = posX;
    this.posY = posY;
    ghost = new Image();
    ghost.src="http://www.frogbug.se/pacman/img/ghost.png";
    ghost.addEventListener("load", function(){
            canvas.drawImage(ghost, this.posX, this.posY)
        }, false);
}

这是在页面加载时启动的函数:

function onLoad() {
    var xy = document.getElementById('canvas');
    canvas = xy.getContext('2d');
    //calculate the x and y for canvas
    x = xy.width;
    y = xy.height;

    //divide the width and length of the canvas to get small cubes
    //which is 40x40
    xtile = Math.floor(x/40);
    ytile = Math.floor(y/40);

    //draw lines around the canvas
    canvas.strokeRect(0, 0, x, y);

    //the array for the map
    var map = getMapArray();

    //draw the map
    drawMap(map);
    //fillCanvas("0010", 0, 40, 40, 40);

    //load the ghost and pacman
    loadPacman(0, 0);
    loadGhost((xtile*40)-40, (ytile*40)-40);
}

提前致谢!您可以在此处查看完整源代码等内容: http://www.picturds.com/pacman_serious/


顺便说一下,我知道我的代码有点凌乱,但我稍后会整理它。 :) - Ms01
你可能会在理解this的工作原理方面遇到一些问题。快速阅读一下:http://www.quirksmode.org/js/this.html - nikc.org
1个回答

4
在加载回调函数中,从 this.posXthis.posY 中删除 this。在该上下文中的 this 是图像元素,而不是当您分配给 this.posX 时的相同 this(即 window)。请保留 HTML 标签。

http://jsfiddle.net/5dkx4/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接