1
我有一個小畫布,每次點擊它時都會繪製隨機矩形。在添加的每個新矩形上,整個畫布被保存到localStorage。從localStorage將圖像加載到畫布只能每秒刷新一次?
當網頁刷新後,最後保存的localStorage圖像被加載。
問題: 我必須刷新兩次以獲取最後一張圖像/抓圖。反射一次給了我一張空白的畫布。爲什麼是這樣?
的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);
}