如何从Canvas上的HTML5 File API中绘制图像? [英] How can I draw an image from the HTML5 File API on Canvas?

查看:86
本文介绍了如何从Canvas上的HTML5 File API中绘制图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在画布上绘制一个用HTML5 File API打开的图像。

I would like to draw an image opened with the HTML5 File API on a canvas.

handleFiles(e)方法,我可以用 e.target.files [0] 访问文件,但是我无法使用 drawImage直接绘制该图像。如何从HTML5画布上的File API中绘制图像?

In the handleFiles(e) method, I can access the File with e.target.files[0] but I can't draw that image directly using drawImage. How do I draw an image from the File API on HTML5 canvas?

以下是我使用的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
    var input = document.getElementById('input');
    input.addEventListener('change', handleFiles);
}

function handleFiles(e) {
    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.drawImage(e.target.files[0], 20,20);
    alert('the image is drawn');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input"/>
<canvas width="400" height="300" id="canvas"/>
</body>
</html>


推荐答案

你有档案不是图像的实例。

获取文件的内容 ,使用 FileReader 。然后将内容传递给 Image 实例,该实例可以在画布上绘制: http:/ /jsfiddle.net/t7mv6/

To get contents of a File, use a FileReader. Then pass the contents to an Image instance, which can be drawn on a canvas: http://jsfiddle.net/t7mv6/.

要获取图像,请使用 new Image() src 必须是引用所选文件的URL。您可以使用 URL.createObjectURL 来获取引用 Blob 的URL(文件也是 Blob ): http:// jsfiddle。 net / t7mv6 / 86 /

To get an image, use new Image(). The src needs to be an URL referencing to the selected File. You can use URL.createObjectURL to get an URL referencing to a Blob (a File is also a Blob): http://jsfiddle.net/t7mv6/86/.

var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function() {
    ctx.drawImage(img, 20,20);
    alert('the image is drawn');
}
img.src = URL.createObjectURL(e.target.files[0]);

注意:请确保在完成后撤消对象网址否则你会泄漏内存。如果你没有做任何太疯狂的事情,你可以在 img.onload URL.revokeObjectURL(img.src) c $ c>功能。

Note: be sure to revoke the object url when you are done with it otherwise you'll leak memory. If you're not doing anything too crazy, you can just stick a URL.revokeObjectURL(img.src) in the img.onload function.

参考文献:

  • https://developer.mozilla.org/en/DOM/File
  • http://html5demos.com/file-api

这篇关于如何从Canvas上的HTML5 File API中绘制图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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