Convert an image to canvas that is already loaded

偶尔善良 提交于 2019-12-29 05:36:19

问题


I am working on a plugin in which I'm converting Image into 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' concept. So 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);

回答1:


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);



回答2:


You can bind click listener to the image and save data-url on click.

var img = document.getElementById("image");
img.addEventListener("click",function(){
    var c = document.createElement("canvas");
    var ctx = c.getContext("2d");
    ctx.canvas.width  = img.getAttribute("width");
    ctx.canvas.height = img.getAttribute("height");
    ctx.drawImage(img,0,0);
    var imgInfo = c.toDataURL("image/png");
    localStorage.setItem("imgInfo", imgInfo);
});


来源:https://stackoverflow.com/questions/26212792/convert-an-image-to-canvas-that-is-already-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!