Saving and loading an image from localStorage

前端 未结 1 675
情深已故
情深已故 2020-11-29 02:20

So basically, I am trying to save an image into localStorage, and then load that same image on the next page.

I came across this great example: http://j

相关标签:
1条回答
  • 2020-11-29 02:40

    Something like this ?

    var img = new Image();
    img.src = 'mypicture.png';
    img.load = function() {
     var canvas = document.createElement('canvas');
     document.body.appendChild(canvas);
     var context = canvas.getContext('2d');
     context.drawImage(img, 0, 0);
     var data = context.getImageData(x, y, img.width, img.height).data;
     localStorage.setItem('image', data); // save image data
    };
    

    Get the localStorage on the second page; try something like this:

    window.onload = function() {
     var picture = localStorage.getItem('image');
     var image = document.createElement('img');
     image.src = picture;
     document.body.appendChild(image);
    };
    
    0 讨论(0)
提交回复
热议问题