问题描述
如何在Canvas中打开图片?它是编码的
How can i open an image in a Canvas ? which is encoded
我使用
var strDataURI = oCanvas.toDataURL();
输出是编码的基础64映像。如何在画布上绘制此图像?
The output is the encoded base 64 image. How can i draw this image on a canvas?
我想使用 strDataURI
并创建图像?它是poosible吗?
如果它不是那么可能是在画布上加载图像的解决方案?
I want to use the strDataURI
and create the Image ? Is it poosible ?
If its not then what possibly can be the solution for loading the image on a canvas ?
推荐答案
给定数据网址,您可以通过将图片的 src
设置为数据网址来创建图片(在网页上或纯粹在JS中)。例如:
Given a data URL, you can create an image (either on the page or purely in JS) by setting the src
of the image to your data URL. For example:
var img = new Image;
img.src = strDataURI;
HTML5 Canvas上下文允许
The drawImage()
method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.
您可以像这样使用它:
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;
编辑:我以前建议在这个空间,在涉及数据URI时使用 onload
处理程序。根据的实验测试,这是不安全的。上述序列创建图像,设置 onload
使用新图像,然后 设置 src
- 某些浏览器必须使用结果。
Edit: I previously suggested in this space that it might not be necessary to use the onload
handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload
to use the new image, and then set the src
—is necessary for some browsers to surely use the results.
这篇关于将图像从数据网址绘制到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!