javascript: upload image file and draw it into a canvas
<html>
<head>
<script type="text/javascript" src="http://fiddle.jshell.net/js/lib/mootools-core-1.4.5-nocompat.js"></script>
<script type="text/javascript">
//<![CDATA[
window.addEvent('load', function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
c.width = img.width;
c.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
});//]]>
</script>
</head>
<body>
<div style="background:#990; width:100%; padding:20px; ">
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
</div>
<canvas id="myCanvas" ></canvas>
</body>
</html>
const EL = (sel) => document.querySelector(sel);
const ctx = EL("#canvas").getContext("2d");
function readImage() {
if (!this.files || !this.files[0]) return;
const FR = new FileReader();
FR.addEventListener("load", (evt) => {
const img = new Image();
img.addEventListener("load", () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, 0, 0);
});
img.src = evt.target.result;
});
FR.readAsDataURL(this.files[0]);
}
EL("#fileUpload").addEventListener("change", readImage);
canvas {display: block;}
<input type='file' id="fileUpload" />
<canvas id="canvas" width="300" height="200"></canvas>
Here is a much simpler method, which doesn't use inefficient data urls:
var canvas = document.getElementById('canvas')
var input = document.getElementById('input')
var c2d = canvas.getContext('2d')
input.onchange=function() {
var img = new Image()
img.onload = function() {
canvas.width = this.width
canvas.height = this.height
c2d.drawImage(this, 0, 0)
URL.revokeObjectURL(this.src)
}
img.src = URL.createObjectURL(this.files[0])
}
<input type=file id=input> <br>
<canvas id=canvas></canvas>