Canvas How to - Display uploaded image file








Question

We would like to know how to display uploaded image file.

Answer


<!--   w  ww  .j av a2s  .  co m-->

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var input = document.getElementById('input');
    input.addEventListener('change', handleFiles);
    function handleFiles(e) {
        var ctx = document.getElementById('canvas').getContext('2d');
        var img = new Image;
        img.src = URL.createObjectURL(e.target.files[0]);
        img.onload = function() {
            ctx.drawImage(img, 20,20);
            alert('the image is drawn');
        }
    }
}//]]>  
</script>
</head>
<body>
<input type="file" id="input"/>
<canvas width="400" height="300" id="canvas"/>
</body>
</html>

The code above is rendered as follows: