How to upload image into HTML5 canvas

JavascriptHtmlHtml5 Canvas

Javascript Problem Overview


I am currently using http://paperjs.org to create an HTML5 canvas drawing app. I want to let users upload images into the canvas. I know I need to make a login and signup but is there an easier way? I have seen the HTML5 drag and drop upload.

Javascript Solutions


Solution 1 - Javascript

I assume you mean, to load an image into the canvas and not uploading the image from the canvas.

It'd probably be a good idea to read through all the canvas articles they have over here https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

But basically what you want to do is create an image in javascript, and set the image.src = to whatever the file location is. In the case of loading images from the user on their end, you're going to want to use the File System API.

Threw together a brief example here: http://jsfiddle.net/influenztial/qy7h5/

function handleImage(e){
    var reader = new FileReader();
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img,0,0);
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);     
}

Solution 2 - Javascript

One doesn't need a FileReader*, it is better to use the URL.createObjectURL method, which will create a symlink directly to the File on disk. This will incur less memory usage, and will have the added benefit to have only one async event to wait for (the one of the img.onload).

document.getElementById('inp').onchange = function(e) {
  var img = new Image();
  img.onload = draw;
  img.onerror = failed;
  img.src = URL.createObjectURL(this.files[0]);
};
function draw() {
  var canvas = document.getElementById('canvas');
  canvas.width = this.width;
  canvas.height = this.height;
  var ctx = canvas.getContext('2d');
  ctx.drawImage(this, 0,0);
}
function failed() {
  console.error("The provided file couldn't be loaded as an Image media");
}

<input type="file" id="inp">
<canvas id="canvas"></canvas>

*IIRC only a few versions of Chrome did support FileReader while not yet supporting URL.createObejctURL, so if you target these very versions, you might need FileReader..

Solution 3 - Javascript

The most optimal way of creating an image consumable by the canvas is to create an ImageBitmap out of the File you get from the input.

This will use an optimized path to produce just what the browser needs to render that image, and will store the bitmap data in the GPU, allowing for fast drawing when asked to.

Given this is a quite recent feature (Safari added support only last year), you may want to use a polyfill like this one of mine.

document.querySelector("input").oninput = async (evt) => {
  try {
    const file = evt.target.files[0];
    const bitmap = await createImageBitmap(file);
    const canvas = document.querySelector("canvas");
    canvas.width = bitmap.width;
    canvas.height = bitmap.height;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(bitmap, 0, 0);
  }
  catch(err) {
    console.error(err);
  }
};

<!-- createImageBitmap polyfill for old browsers --> <script src="https://cdn.jsdelivr.net/gh/Kaiido/createImageBitmap/dist/createImageBitmap.js"></script>
<input type="file">
<canvas></canvas>

Solution 4 - Javascript

<script>
window.onload = function() {
var canvas=document.getElementById(“drawing”); // grabs the canvas element
var context=canvas.getContext(“2d”); // returns the 2d context object
var img=new Image() //creates a variable for a new image
 
img.src= “images/vft.jpg// specifies the location of the image
context.drawImage(img,20,20); // draws the image at the specified x and y location
}
</script>

Check http://www.pageresource.com/html5/insert-image-in-canvas/">Demo</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1438026View Question on Stackoverflow
Solution 1 - JavascriptDerekRView Answer on Stackoverflow
Solution 2 - JavascriptKaiidoView Answer on Stackoverflow
Solution 3 - JavascriptKaiidoView Answer on Stackoverflow
Solution 4 - Javascriptharikrishnan.n0077View Answer on Stackoverflow