javascriptjquerycanvasbase64

Convert an image to canvas that is already loaded


I am working on a plugin in which I'm converting image into a canvas and storing as data URL.

This function triggers on load event but how can I convert an image which is already there on the page? (Don't want to refresh the page or load any image again).

I tried using the filereader() function but that also works on onload event.

But how can I save the image as data URL when the user clicks on the image?

image.addEventListener("load", function () {
                
    var imgCanvas = document.createElement("canvas"),
        imgContext = imgCanvas.getContext("2d");
        imgCanvas.width = image.width;
        imgCanvas.height = image.height;
    
        imgContext.drawImage(image, 0, 0, image.width, image.height);       
        imgInfo = imgCanvas.toDataURL("image/png");
        
        localStorage.setItem("imgInfo", imgInfo);

}, false);

Solution

  • Now it works perfectly.If you create a temporary image element using javascript then store it in localStorage. This worked for me hope it'll help others too:

    image = document.createElement('img');
    document.body.appendChild(image);
    image.setAttribute('style','display:none');
    image.setAttribute('alt','script div');
    image.setAttribute("src", path);
    
    var imgCanvas = document.createElement("canvas"),
    imgContext = imgCanvas.getContext("2d");
    
    // Make sure canvas is as big as the picture
    imgCanvas.width = image.width;
    imgCanvas.height = image.height;
    
    // Draw image into canvas element
    imgContext.drawImage(image, 0, 0, image.width, image.height);
    // Save image as a data URL
    imgInfom = imgCanvas.toDataURL("image/png");
    localStorage.setItem("imgInfo",imgInfom);
    document.body.removeChild(image);