admin管理员组

文章数量:1388844

I am new to HTML5 and the canvas element and in the last few weeks I have been trying to understand it better. Anyways I am getting a Uncaught TypeError: Type error when I am trying to change the red square from this code / to this image .png. But when I try to I just always get that Uncaught TypeError: Type error. Here is the code I have currently /.

If you need me to explain something better just ask.

I am new to HTML5 and the canvas element and in the last few weeks I have been trying to understand it better. Anyways I am getting a Uncaught TypeError: Type error when I am trying to change the red square from this code http://jsfiddle/kmHZt/10/ to this image https://i.sstatic/dmLmn.png. But when I try to I just always get that Uncaught TypeError: Type error. Here is the code I have currently http://jsfiddle/cCDFs/.

If you need me to explain something better just ask.

Share Improve this question edited Mar 1, 2013 at 20:11 Andreas 21.9k7 gold badges51 silver badges58 bronze badges asked Mar 1, 2013 at 20:07 AnzwurAnzwur 6131 gold badge6 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You're trying to pass a URL into drawImage, which you can't do - you need to load an image element and pass it instead, after the image has finished loading.

This article has examples of what I'm describing.

The code would end up something like this:

var img = new Image();
img.onload = function() {
    context.drawImage(img, 2, 2);
}
img.src = 'http://i.imgur./k73egsW.png';

In fact, your code does it already when it loads and draws the tiles.

The first argument you need to pass to drawImage is an Image or a Canvas object, not a string;

I didn't quite get what you try to achieve with your code, but if you replace your draw() call to your function by code like this:

var otherImageObj = new Image();
otherImageObj.onload = function() {
        context.clearRect(0,0,canvas.width, canvas.height);
        for (y = 0; y <= vHeight; y++) {
            for (x = 0; x <= vWidth; x++) {
                theX = x * 32;
                theY = y * 32;
                context.drawImage(tiles[board[y+vY][x+vX]], theX, theY, 32, 32);
            }
        }
        context.drawImage(otherImageObj, 2, 2);

};
otherImageObj.src = "http://i.imgur./k73egsW.png";

Your code actually works, albeit, getting a "403 (Forbidden)" error for your image.

本文标签: javascriptUncaught TypeError Type error with drawImageStack Overflow