0

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

1 回答 1

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> 
于 2013-05-06T18:06:01.700 回答