将图像从数据 URL 绘制到画布 [英] Drawing an image from a data URL to a canvas

查看:38
本文介绍了将图像从数据 URL 绘制到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Canvas 中打开图像?这是编码

How can i open an image in a Canvas ? which is encoded

我正在使用

var strDataURI = oCanvas.toDataURL(); 

输出是编码的 base 64 图像.如何在画布上绘制此图像?

The output is the encoded base 64 image. How can i draw this image on a canvas?

我想使用 strDataURI 并创建图像?可以吗?
如果不是,那么在画布上加载图像的解决方案可能是什么?

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 ?

推荐答案

给定一个数据 URL,你可以通过设置图像到您的数据 URL.例如:

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;

drawImage() 方法 HTML5 Canvas Context 允许您将图像(或画布或视频)的全部或部分复制到画布上.

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.

这篇关于将图像从数据 URL 绘制到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆