将图像转换为已加载的画布

时间:2014-10-06 08:52:40

标签: javascript jquery canvas base64

我正在开发一个插件,我将Image转换为Canvas并存储为数据url。此功能触发' load'事件,但我如何转换页面上已有的图像? (不要刷新页面或再次加载任何图像)。我尝试使用Filereader()函数,但这也适用于' onload'概念。那么当用户点击图像时如何将图像保存为数据网址呢?

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

2 个答案:

答案 0 :(得分:4)

现在它完美无缺。如果您使用javascript创建临时图像元素,则将其存储在localStorage中。这对我有用,希望它能帮助别人

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

答案 1 :(得分:0)

您可以将点击侦听器绑定到图像,并在点击时保存data-url。

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