Well i have a function in javascript:
function store_data(){
var img=document.createElement("img");
/*var img=new Image();
img.onload = function() {
context.drawImage(img, 0, 0);
};*/
img.src= URL; //js global var
var height=parseInt(img.naturalHeight,10);
var width=parseInt(img.naturalWidth,10);
var canvas = document.getElementById('myCanvas');
canvas.setAttribute("width", width);
canvas.setAttribute("height", height);
var context = canvas.getContext('2d');
context.drawImage(img,0,0);
canvas.style.width="100%";
var data=(canvas.toDataURL("image/png"));
localStorage.setItem("data", data);
}
The first time when is called store a string like "data;" in localStorage is incomplete the image is like a "data64;aotehtahotetav...". But when i call for second time the data is stored fine. Why happens that?
Perhaps i should load the image in a img of the dom loaded? The image is stored for using in draw late.
Like Michael has already mentioned your code is saving the image's data to localStorage before it has completely downloaded. The second time the image already exists in cache.
Maybe try loading the image onto the canvas when the onload event fires like so
function store_data() {
var img = new Image();
img.src = URL; //js global var
img.onload = function( ) {
var canvas = document.getElementById( 'myCanvas' );
canvas.setAttribute( "width", img.width );
canvas.setAttribute( "height", img.height );
var context = canvas.getContext( '2d' );
context.drawImage( img, 0, 0 );
canvas.style.width = "100%";
var data = canvas.toDataURL("image/png");
localStorage.setItem( "data", data );
}
}
如果您不在img.onload
数据存储,那么当您将图像存储在本地存储中时,无法确定图像的数据是否已完全下载,并且您将获得不一致的数据长度。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.