jQuery 动态添加图像到画布

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6944382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:35:55  来源:igfitidea点击:

Dynamically add image to canvas

jqueryhtmldynamiccanvas

提问by Ignaty Nikulin

Good day folks.

美好的一天,伙计们。

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

我想知道有什么方法可以将图像从用户计算机动态添加到画布。

For example I have:

例如我有:

<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.

请告诉我要遵循的任何路径。

Thank you!

谢谢!

回答by Sanghyun Lee

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.

为此,您应该熟悉 HTML5 Canvas API 和 File API。当然,此功能在仅支持 HTML5 API 的浏览器中可用。

The process to do this is:

执行此操作的过程是:

  1. Dispatch a changeevent to file input element.
  2. Get the uploaded file from the event handler and get a data URL by using the FileReaderobject.
  3. Make an imgelement with the data URL and draw it on the canvas.
  1. change事件分派到文件输入元素。
  2. 从事件处理程序中获取上传的文件并使用FileReader对象获取数据 URL 。
  3. img使用数据 URL 创建一个元素并将其绘制在画布上。

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

我在 jsfiddle 上做了一个简单的例子。代码如下所示:

<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>

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

有很多关于像这样这样的文件 API 的好教程。