javascript - 将图像转换为已加载的 Canvas

标签 javascript jquery canvas base64

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

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

最佳答案

现在它完美地工作了。如果您使用 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);

关于javascript - 将图像转换为已加载的 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26212792/

相关文章:

android - 在操作栏选项卡上方放置/重叠(z-index) View

javascript - 在 Safari 上,在 Canvas 中渲染 mathML 失败。图片加载回调未触发

javascript - RequestAnimationFrame 不适用于简单 Canvas

javascript - 将 li 从一个 ul 移动到另一个 jQuery

javascript - Jquery - 条件为 true 的第一个实例

javascript - 我的类原型(prototype)中的 Ajax 运行函数?

javascript - CSS/jQuery - 响应式设计让关闭按钮留在右上角

jquery - 什么是 "scroll-linked positioning effect"的替代方案来防止性能问题?

javascript - Ajax 表单发布不起作用 - 似乎从未提交

javascript - 警报声明不起作用