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

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

问题描述

大家好.

我想知道有没有办法将用户计算机中的图像动态添加到画布上.

例如我有:

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

如果用户选择带有输入的图像,则会将其添加到画布中.

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

谢谢!

解决方案

要做到这一点,您应该熟悉 HTML5 Canvas API 和 File API.当然,此功能在仅支持两种 HTML5 API 的浏览器中可用.

执行此操作的过程是:

  1. 向文件输入元素发送 change 事件.
  2. 从事件处理程序中获取上传的文件并使用 或 这个.

    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!

    解决方案

    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.

    The process to do this is:

    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.

    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>
    

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

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

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