Nigel Brook
Nigel Brook

Reputation: 17

adding images to a html5 canvas

I'm trying to add an image to my canvas but it doesn't seem to work I've taken a look and can't see anything wrong with my code but maybe someone else can.

This is my JS file.

if (window.addEventListener) 
{
    window.addEventListener( 'load', onLoad, false);
}

function onLoad()
{
var canvas;
var context;

function initialise() 
{
    canvas = document.getElementById('canvas'); 

    if (!canvas.getContext)
    { 
        alert('Error: no canvas.getContext!'); 
        return; 
    }

    context = canvas.getContext('2d'); 
    if (!context)
    { 
        alert('Error: failed to getContext!'); 
        return; 
    }

}
}

function draw()
{
    var sun = new Image();
    sun.src = 'images.sun.png';
    context.drawImage(sun, 100, 100);
}

onLoad();
draw(); 

Here's my HTML mabye this will help find the problem

<!doctype html>
    <html>
        <head>
            <title>Test</title> <script type="text/javascript" src="javascript/canvas.js"></script>
        </head>
        <body>
            <canvas id="canvas" width="800" height="600">
                Your browser does not support the canvas tag
            </canvas>

        </body>
    </html>

Upvotes: 0

Views: 3511

Answers (2)

andy
andy

Reputation: 132

the problem is, that you declare canvas & context in onLoad() but try to access it in draw().

so, by making them global, the problem is solved:

var canvas;
var context;

if (window.addEventListener) {
    window.addEventListener('load', function(){
        onLoad();
    }, false);
}

function onLoad() {
    initialise();
    draw();
}

function initialise() {
    canvas = document.getElementById('canvas');

    if (!canvas.getContext) {
        alert('Error: no canvas.getContext!');
        return;
    }

    context = canvas.getContext('2d');
    if (!context) {
        alert('Error: failed to getContext!');
        return;
    }

}

function draw() {
    var sun = new Image();
    sun.addEventListener('load', function(){
        context.drawImage(sun, 100, 100);
    }, false);
    sun.src = 'http://puu.sh/1yKaY';
}

Upvotes: 1

Nikola Ninkovic
Nikola Ninkovic

Reputation: 1262

Try to draw image on it's onload event

 sun.onload = function() {
    context.drawImage(sun, 100, 100);
 };

Upvotes: 0

Related Questions