在将其绘制到屏幕外画布后,Javascript图像无法在画布上绘图

时间:2016-04-29 00:13:49

标签: javascript html5 canvas

我有一个想要渲染到画布的图像。当我像这样呈现它时:

context.drawImage(image, x, y);

它按预期工作。但是,当我这样做时:

if (image.loaded)
    image = getPreRendered(image);
...
var renderedImages = [];
var tmpImage = null;
function getPreRendered(img) {
    imageIndex = ("" + img.src);
    tmpImage  = cachedSprays[tmpIndex];
    if (tmpImage == undefined) {
        var tmpCanvas = document.createElement("canvas");
        var tmpContext = tmpCanvas.getContext('2d');
        tmpCanvas.width = 50;
        tmpCanvas.height = 50;
        tmpContext.drawImage(img, 0, 0, 100, 100);
        tmpContext.imageSmoothingEnabled = false;
        tmpContext.webkitImageSmoothingEnabled = false;
        tmpContext.mozImageSmoothingEnabled = false;
        tmpContext.drawImage(tmpCanvas, 0, 0, 50, 50, 0, 0, 100, 100);
        tmpImage = tmpCanvas;
        cachedSprays[imageIndex] = tmpImage ;
    }
    return tmpImage ;
}

但是,当我这样做时,画布上不再显示图像。

图像的创建方式如下:

var image = new Image();
image.loaded = false;
image.onload = function () {
    image.loaded = true;
};

1 个答案:

答案 0 :(得分:1)

AJAX和图片调用 asyncronous 。图像将加载/但会在图像仍在加载时调用该函数。

var image = new Image();
image.onload = function () {
    // call here your render canvas function:
    getPreRendered( image );
};
image.src = "nOOdes.jpg"