我正在尝试编写一个安全失败的程序,使用画布绘制非常大的图像(60 MB可能是上限,而10 MB则是下限)。我很久以前就发现调用画布的同步函数toDataURL
通常会导致浏览器崩溃,因此我已经改用了toBlob
方法,并使用填充物来实现跨浏览器兼容性。我的问题是:使用URL.createObjectURL(blob)
方法创建的Blob URL可以持续多长时间?
我想知道是否有一种缓存Blob URL的方法,使其在浏览器会话结束后仍然存在,以便某人在某个时间点渲染图像的某个部分,关闭浏览器,然后通过将Blob URL读入画布再次开始,并从离开时的点继续完成它。我注意到这个可选的autoRevoke参数可能是我正在寻找的,但我想确认一下我所尝试做的事情是否实际上是可能的。不需要在您的答案中提供代码示例,除非它涉及不同的解决方案,我只需要回答是否可以使用此方法或其他方法使Blob URL持续存在于会话之间。(如果页面崩溃并像“恢复会话”选项一样运行,这也将非常有用。)
我正在考虑像这样的东西:
function saveCache() {
var canvas = $("#canvas")[0];
canvas.toBlob(function (blob) {
/*if I understand correctly, this prevents it from unloading
automatically after one asynchronous callback*/
var blobURL = URL.createObjectURL(blob, {autoRevoke: false});
localStorage.setItem("cache", blobURL);
});
}
//assume that this might be a new browser session
function loadCache() {
var url = localStorage.getItem("cache");
if(typeof url=="string") {
var img = new Image();
img.onload = function () {
$("#canvas")[0].getContext("2d").drawImage(img, 0, 0);
//clear cache since it takes up a LOT unused of memory
URL.revokeObjectURL(url);
//remove reference to deleted cache
localStorage.removeItem("cache");
init(true); //cache successfully loaded, resume where it left off
};
img.onprogress = function (e) {
//update progress bar
};
img.onerror = loadFailed; //notify user of failure
img.src = url;
} else {
init(false); //nothing was cached, so start normally
}
}
请注意,我不确定这将按照我预期的方式工作,因此任何确认都将是很棒的。
编辑刚刚意识到sessionStorage
与localStorage
不是同一件事:P