putImageData / Canvas - 如何在此处转储像素阵列?

时间:2010-09-01 15:10:00

标签: javascript graphics html5 canvas pixel

在我之前使用过getImageData之后,如何重新绘制像素数组?我认为有道理的方式给了我错误:指定了无效或非法的字符串“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 个答案:

答案 0 :(得分:1)

我想你可能需要把

main()

调用填充backgroundData的loadImage调用。可能是在图像加载之前调用main。

var backgroundImg = loadImage(background, function() {
    backgroundData = getDataFromImage(backgroundImg);
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    main();
});