1

クリックするたびにランダムな長方形が描画される小さなキャンバスがあります。新しい長方形が追加されるたびに、キャンバス全体がlocalStorageに保存されます。

Web ページが更新されると、localStorage から最後に保存された画像が読み込まれます。

問題: 最後の画像/キャプチャを取得するために、2 回更新する必要があります。一度リフレッシュすると、空白のキャンバスしか表示されません。どうしてこれなの?

インデックス.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);
}
4

1 に答える 1

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'];
}
于 2012-08-14T07:13:26.770 に答える