views:

71

answers:

1

How do I redraw the pixel array after I after I have previously used getImageData? The way that I thought made sense gives me the error: An invalid or illegal string was specified" code: "12

function makeImage(canvasId, background, object) {

    var canvas = document.getElementById(canvasId);
    var ctx = canvas.getContext('2d');
    var backgroundData = null;
    var objectData = null;

    //Get image Data
    function getDataFromImage(img) {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.clearRect(0, 0, img.width, img.height);
        ctx.drawImage(img, 0 ,0);
        return ctx.getImageData(0, 0, img.width, img.height);
    }

    //Load image
    function loadImage(src, callback) {
        var img = document.createElement('img');
        img.onload = callback;
        img.src = src;
        return img;
    }

    //Get Background Image Data
    var backgroundImg = loadImage(background, function() {
        backgroundData = getDataFromImage(backgroundImg);
        ctx.clearRect(0, 0, canvas.width, canvas.height); 
        });

    //Get Object Image Data
    var objectImg = loadImage(object, function() {
        objectData = getDataFromImage(objectImg);
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        });

    main();

    function main() {
        ctx.putImageData(backgroundData, 0, 0); //Try to redraw the background??
    }
 };
+1  A: 

I think you might need to put the

main()

call inside the loadImage call that is populating backgroundData. It could be that main is called before the image has loaded.

var backgroundImg = loadImage(background, function() {
    backgroundData = getDataFromImage(backgroundImg);
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    main();
});
Castrohenge
spot on. thanks that was driving me mad! that explains all the problems in my actual project now, just calling before things have loaded. cheers.
davivid