javascript - DataURL not returning value -
i have created function stores datauri of image in local storage.
data stored in local storage if try value function i.e. return statement, "undefined" value. probably, function returning value before converting dataurl.
need help.
here code:
function getimagedataurl(local_name,w,h,i){ var data, canvas, ctx; var img = new image(); img.onload = function(){ canvas = document.createelement('canvas'); canvas.width = w; canvas.height = h; ctx = canvas.getcontext("2d"); ctx.drawimage(img,0,0,w,h); try{ data = canvas.todataurl("image/png"); localstorage.setitem(local_name,data); }catch(e){ console.log("error "+e) } } try{ img.src = i; }catch(e){} return data;
}
the problem you're taking asynchronous value , trying return synchronously. img.onload
being called way after function returns. common pattern in javascript pass function function call when done:
function getimagedataurl(local_name, w, h, i, callback) { var data, canvas, ctx; var img = new image(); img.onload = function (){ canvas = document.createelement('canvas'); canvas.width = w; canvas.height = h; ctx = canvas.getcontext("2d"); ctx.drawimage(img,0,0,w,h); callback(canvas.todataurl("image/png")); } img.src = i; } getimagedataurl('image', 100, 100, 'image.png', function (data) { localstorage.setitem(local_name, data); console.log(data); });
one problem might run cross-domain security feature. if draw image foreign domain (that is, 1 that's different page javascript), "taint" canvas, , you're no longer able access image data using todataurl
.
to bypass this, you'll either need remote server implement cors approval or run proxy server looks image coming own server.
Comments
Post a Comment