Aloso Aloso - 3 months ago 16
Javascript Question

javascript: upload image file and draw it into a canvas

I work at a web application for painting images. I use a CANVAS element and javascript to draw on it, but I have a problem: how can I load an image from the pc of the user and draw it on the canvas? I don't want to save it on the server, only on the webpage!

Here is a shortened version of the code (the full code would be too long):

HTML:

Open file: <input type="file" id="fileUpload" accept="image/*" /><br />
<canvas id="canvas" onmousemove="keepLine()" onmouseup="drawLine()" onmousedown="startLine()" width="900" height="600" style="background-color:#ffffff;cursor:default;">
Please open this website on a browser with javascript and html5 support.
</canvas>


javascript:

var x = 0;
var y = 0;
var clicked = false;

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

context.strokeStyle = "black";
context.lineCap = "round";

canvas.addEventListener('mousemove', function(e) { getMousePos(canvas, e); }, false);

takePicture.onchange = function (event) {
var files = event.target.files,
file;
if (files && files.length > 0) {
file = files[0];
processImage(file);
}
};

function processImage(file) {
var reader = new FileReader();
reader.readAsDataUrl(file)
reader.onload = function(e) {
var img = new Image();
img.onload = function() {
context.drawImage(img, 100,100)
}
img.src = e.target.result;
}
}

// functions for drawing (works perfectly well)
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
x = evt.clientX - rect.left;
y = evt.clientY - rect.top;
}

function startLine() {
context.moveTo(x,y);
context.beginPath();
clicked = true;
}

function keepLine() {
if(clicked) {
context.lineTo(x,y);
context.stroke();
context.moveTo(x,y);
}
}

function drawLine() {
context.lineTo(x,y);
context.stroke();
clicked = false;
}


There's no copyright

Answer

function el(id){return document.getElementById(id);} // Get elem by ID

var canvas  = el("canvas");
var context = canvas.getContext("2d");

function readImage() {
    if ( this.files && this.files[0] ) {
        var FR= new FileReader();
        FR.onload = function(e) {
           var img = new Image();
           img.onload = function() {
             context.drawImage(img, 0, 0);
           };
           img.src = e.target.result;
        };       
        FR.readAsDataURL( this.files[0] );
    }
}

el("fileUpload").addEventListener("change", readImage, false);
<input type='file' id="fileUpload" />
<canvas id="canvas" width="900" height="600"></canvas>  

Comments