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

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

问题描述

美好的一天。

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

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.

请告诉我任何路径。

谢谢!

推荐答案

为此,您应该熟悉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
    对象获取数据网址。 li>
  3. 使用数据网址创建 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的好教程,例如 this

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

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

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