将图像从localStorage加载到画布只能每隔一次刷新一次吗?

时间:2012-08-09 22:11:27

标签: javascript html5 canvas local-storage image

我有一个小画布,每次点击它时都会绘制随机矩形。在添加的每个新矩形上,整个画布将保存到 localStorage

刷新网页时,会加载localStorage中最后保存的图像。

问题: 我必须刷新两次才能获得最后一张图像/捕获。 Rrefreshing曾经给我一个空白的画布。这是为什么?

的index.html:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="./script.js"></script>
    </head>
    <body>
        <canvas onclick="draw(this, event);" id="drawarea" height="240" width="320" style="border:1px solid black;">
        </canvas>
    </body>
</html>

的script.js:

"use strict;"

window.onload=function(){
    c=document.getElementById("drawarea");
    if (c) initCanvas(c);
};

function initCanvas(canvas){
    // Load last canvas
    loadLastCanvas(canvas);
}

function draw(canvas, event){

    // Draw at random place
    ctx=c.getContext("2d");
    ctx.fillStyle="#ff0000";
    ctx.beginPath();
    ctx.fillRect (250*Math.random()+1, 220*Math.random()+1, 40, 30);
    ctx.closePath();
    ctx.fill();

    // Save canvas
    saveCanvas(canvas);
}

function saveCanvas(c){
    localStorage['lastImgURI']=c.toDataURL("image/png");
}

function loadLastCanvas(c){
    if (!localStorage['lastImgURI']) return;
    img = new Image();
    img.src= localStorage['lastImgURI'];
    ctx=c.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
}

1 个答案:

答案 0 :(得分:1)

问题是img.src = ""是异步调用。因此,您必须向onload事件添加回调。有关详细信息,请参阅html5canvastutorials.com

function loadLastCanvas(c){
    if (!localStorage['lastImgURI']) return;
    img = new Image();
    img.onload = function() {
       ctx=c.getContext("2d");
       ctx.drawImage(img, 0, 0, img.width, img.height);
    };
    img.src= localStorage['lastImgURI'];
}