Search code examples
html5-canvasimage-viewer

HTML5 Image Viewer (Browse Add Image)


http://jsfiddle.net/KFEAC/2/

I'd like to learn how to add a image from my hard drive into an HTML5 canvas. I don't wanna upload it, just load it from my hard drive dynamically from a browse window after a button is clicked.

I do believe this is possible without PHP.

Can anyone help?

HTML:

<input type="file" id="openimg"> <input type="button" id="load" value="Load" style="width:100px;"><br/>

Width and Height (px): <input type="text" id="width" style="width:100px;">, <input type="text" id="height" style="width:100px;"><br/>

<canvas id="myimg" width="300" height="300"></canvas>

JavaScript/JQuery:

$(function(){
    $("canvas#myimg").draggable();

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

    function draw() {
        var chosenimg = $("#openimg").val();
        var w = parseInt($("#width").val());
        var h = parseInt($("#height").val());
        canvas.width = w;
        canvas.height = h;

        var img = new Image();
        img.onload = function () {
            context.drawImage(img,0,0,img.width,img.height,0,0,w,h);
        }
        img.src = $("#openimg").val();}

    $("#width").val(150);
    $("#height").val(150);

    $("#load").click(function(){ draw(); });
});

Solution

  • <!doctype html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    
    <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>
    
    <script>
    $(function(){
    
        var canvas = document.getElementById("myimg");
        var context = canvas.getContext("2d");
    
        function draw() {
            var chosenimg = $("#openimg").val();
            var w = parseInt($("#width").val());
            var h = parseInt($("#height").val());
            canvas.width = w;
            canvas.height = h;
    
            var img = new Image();
            img.onload = function () {
              context.drawImage(img,0,0,img.width,img.height,0,0,w,h);
            console.log(img.src);
            }
            img.src = $("#openimg").val();
        }
    
        $("#width").val(150);
        $("#height").val(150);
        $("#load").click(function(){ draw(); });
    
    }); // end $(function(){});
    </script>
    
    </head>
    
    <body>
        <input type="file" id="openimg">
        <input type="button" id="load" value="Load" style="width:100px;"><br/>
        Width and Height (px): 
        <input type="text" id="width" style="width:100px;">,
        <input type="text" id="height" style="width:100px;"><br/>
        <canvas id="myimg" width="300" height="300"></canvas>
    </body>
    </html>