HTML5图像浏览器(浏览添加图像)

时间:2013-05-06 16:37:58

标签: html5-canvas image-viewer

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

我想学习如何将硬盘中的图像添加到HTML5画布中。我不想上传它,只需在点击按钮后从浏览窗口动态加载它。

我相信没有PHP就可以做到这一点。

有人可以帮忙吗?

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(); });
});

1 个答案:

答案 0 :(得分:1)

<!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>