Amauri
Amauri

Reputation: 550

drawImage() of canvasrenderingcontext2d not displaying img

I'm trying to learn to use drawImage(), all nodes are created; the image is 1000x500px but never displays

<head>
</head>
<body>
    <script type = "text/javascript">
        var body, canvas, img, cxt;
        body = document.getElementsByTagName("body")[0];
        
        canvas = document.createElement("canvas");
        canvas.style.width = "1000px";
        canvas.style.height = "500px";
        body.appendChild(canvas);
        img = document.createElement("img");
        cxt = canvas.getContext("2d");
        img.onload = function () {
            cxt.drawImage(img,0,0,1000,500,0,0,1000,500);

        }

        img.src = "/clouds.png";
    </script>
</body>

Upvotes: 2

Views: 299

Answers (2)

Amauri
Amauri

Reputation: 550

Part of the image I was using had was white. And so it just so happend that that was the part of the image which I was cropped.

Upvotes: 1

Banana
Banana

Reputation: 7463

Your code runs before your DOM is being loaded, you are trying to append elements to the body before its even created.

you need to wrap your code in a block that will run once the DOM is ready, or better, once the entire window's content is fully loaded:

Example

window.onload  = function () {
    var body, canvas, img, cxt;
    body = document.getElementsByTagName("body")[0];

    canvas = document.createElement("canvas");
    canvas.style.width = "400px";
    canvas.style.height = "400px";
    body.appendChild(canvas);
    img = document.createElement("img");
    cxt = canvas.getContext("2d");
    img.onload = function () {
        cxt.drawImage(img, 0, 0, 400, 400, 0, 0, 350, 200);
    }
    img.src = "http://cdn.sstatic.net/stackoverflow/img/[email protected]?v=fde65a5a78c6";
};

Upvotes: 1

Related Questions