动态地将图像添加到画布 [英] Dynamically add image to canvas

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

问题描述

美好的一天。

我想知道有没有办法从用户电脑动态添加图片到画布。

Im wondering is there any way to dynamically add image from user computer to canvas.

例如我有:

<canvas id="canvas"></canvas>
<input type="file" id="image-chooser">

如果用户将输入的图片添加到画布中。

If user pick image with input it's added to canvas.

请显示我要追踪的路径。

Show me any path to follow, please.

谢谢!

推荐答案

为此,您应该熟悉HTML5 Canvas API和File API。当然,这个功能在浏览器中只支持HTML5 API。

To do this you should be familiar with the HTML5 Canvas API and the File API. And of course, this feature is available in the browsers only support both HTML5 APIs.

执行此操作的过程是:


  1. 向文件输入元素发送一个更改事件。

  2. 从上传的文件事件处理程序,并使用 FileReader
    对象获取数据URL。

  3. 使用数据URL创建一个 img 元素,并在画布上绘制。

  1. Dispatch a change event to file input element.
  2. Get the uploaded file from the event handler and get a data URL by using the FileReader object.
  3. Make an img element with the data URL and draw it on the canvas.

我在jsfiddle上创建了一个简单的示例。代码如下:

I made a simple example on jsfiddle. The code looks like this:

<canvas id="canvas"></canvas>
<input type="file" id="file-input">
<script>
$(function() {
    $('#file-input').change(function(e) {
        var file = e.target.files[0],
            imageType = /image.*/;

        if (!file.type.match(imageType))
            return;

        var reader = new FileReader();
        reader.onload = fileOnload;
        reader.readAsDataURL(file);
    });

    function fileOnload(e) {
        var $img = $('<img>', { src: e.target.result });
        $img.load(function() {
            var canvas = $('#canvas')[0];
            var context = canvas.getContext('2d');

            canvas.width = this.naturalWidth;
            canvas.height = this.naturalHeight;
            context.drawImage(this, 0, 0);
        });
    }
});
</script>

有很多有关File API的好教程,如这个

There are plenty of good tutorials about the File API like this or this.

这篇关于动态地将图像添加到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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