Convert an image to canvas that is already loaded(将图像转换为已加载的画布)
问题描述
我正在开发一个插件,在该插件中我将图像转换为画布并存储为数据 url.此函数触发加载"事件,但如何转换页面上已经存在的图像?(不想刷新页面或再次加载任何图像).我尝试使用 Filereader() 函数,但这也适用于onload"概念.那么如何在用户点击图片时将图片保存为数据url呢?
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);
推荐答案
现在完美运行.如果您使用 javascript 创建临时图像元素,然后将其存储在 localStorage 中.这对我有用,希望它也能帮助其他人
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);
这篇关于将图像转换为已加载的画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将图像转换为已加载的画布
基础教程推荐
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01