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

查看:30
本文介绍了如何从 Canvas 上的 HTML5 文件 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] 访问文件,但我不能直接使用 <代码>绘制图像.如何从 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>

推荐答案

您有一个不是图像的 File 实例.

You have a File instance which is not an image.

要获取图像,请使用 new Image().src 必须是引用所选 File 的 URL.您可以使用 URL.createObjectURL 来获取引用 Blob 的 URL(File 也是一个 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]);

注意: 一定要在完成后撤消对象 url,否则会泄漏内存.如果你不做任何太疯狂的事情,你可以在 img.onload 函数中粘贴一个 URL.revokeObjectURL(img.src) .

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.

参考文献:

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

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