Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

jquery - Dynamically add image to canvas

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...