将图像从本地存储加载到画布仅每秒刷新一次

Loading image from localStorage to canvas works only every second refresh?

本文关键字:刷新 一次 布仅每 图像 存储 加载      更新时间:2023-09-26

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

刷新网页时,将加载本地存储中上次保存的图像。

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

索引.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>

脚本.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);
}

问题是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'];
}