3

我正在尝试将多个图像添加到Html5 画布,但每次我尝试删除最后一个图像并显示最新的图像时它都会失败。这是我的代码:

var imgArray = ['abc.png','455.jpg'];
    for(i = 0; i < 2; i++){
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext("2d");
        var imageObj = new Image();
        imageObj.src = imgArray[i];
        imageObj.onload = function() {
        context.drawImage(this,0,0);
    };
}

如果我运行此代码,它会在画布上显示第二张图像并删除第一张图像。有没有办法保留两个图像?

4

2 回答 2

5

实际上 onLoad 总是使用变量的最后一个值。所以存储(计算) img x, y之前的坐标。像这样:

imageObj.setAtX = i * 10;
imageObj.setAtY = i * 10;
imageObj.onload = function() {
     context.drawImage(this, this.setAtX, this.setAtY);
};
于 2012-06-27T13:29:14.473 回答
-1

我用easeljs试过了。这可能会帮助你。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Upload and display images on HTML5 Canvas</title>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">  
    <script src="http://code.createjs.com/easeljs-0.5.0.min.js"></script> 
    <script type="text/javascript" src="libs/upclick-min.js"></script>
</head>
<body onload="init()">
    <div>
        <input id="uploader" type="button" value="Upload picture from hard disk">       
    </div>
    <canvas  width="1000" height="550" id="canvas"></canvas>
    <script type="text/javascript">
        var canvas;
        var stage;      
        var uploader = document.getElementById('uploader');
        /**
         * UPLOAD SCRIPT 
         * This script uses the upclick-min.js library to upload files on a webserver folder
         * using a PHP script ("upload/upload.php")
         * Project homepage: http://code.google.com/p/upload-at-click/
         */
        upclick(
        {
          element: uploader,
          action: 'upload/upload.php', 

          onstart:
            function(filename)
            {
              //alert('Start upload: '+filename);
            },

          oncomplete:
            function(response_data) 
            {
              // Check upload Status
              if (response_data != "FAIL") {      
                // Draw the picture into Canvas     
                // "response_data" contains the image file name returned from the PHP script
                displayPicture("upload/" + response_data);
                }
            }
        });
        /**
         * Init 
         */

        init = function () {
            canvas = document.getElementById("canvas");
            stage = new createjs.Stage(canvas);
        }
        /**
         * Load and display the uploaded picture on CreateJS Stage 
         */
        displayPicture = function (imgPath) {
            var image = new Image();
            image.onload = function () {
                // Create a Bitmap from the loaded image
                var img = new createjs.Bitmap(event.target)

                // scale it
                img.scaleX = img.scaleY = 0.5;

                /// Add to display list
                stage.addChild(img);

                //Enable Drag'n'Drop 
                enableDrag(img);

                // Render Stage
                stage.update(); 
            }
            // Load the image
            image.src = imgPath;
        }
        /**
         * Enable drag'n'drop on DisplayObjects
         */
        enableDrag = function (item) {
            // OnPress event handler
            item.onPress = function(evt) {
                var offset = {  x:item.x-evt.stageX, 
                                y:item.y-evt.stageY};

                // Bring to front
                stage.addChild(item);

                // Mouse Move event handler
                evt.onMouseMove = function(ev) {

                    item.x = ev.stageX+offset.x;
                    item.y = ev.stageY+offset.y;
                    stage.update();
                }
            }
        }
    </script>   
</body>
</html>

上传/上传.php

<?php
$tmp_file_name = $_FILES['Filedata']['tmp_name'];
$ok = move_uploaded_file($tmp_file_name, $_FILES['Filedata']['name']);

// This message will be passed to 'oncomplete' function
echo $ok ? $_FILES['Filedata']['name'] : "FAIL";

?>

lib/upclick-min.js

function upclick(d){var g={element:null,action:"about:blank",action_params:{},maxsize:0,onstart:null,oncomplete:null,dataname:"Filedata",target:null,zindex:"auto"};for(var h in g)d[h]=d[h]?d[h]:g[h];var k=d.element;if(typeof k=="string")k=document.getElementById(k);var e=k.ownerDocument,b,c=e.createElement("div"),n="frame"+(new Date).getTime().toString().substr(8);c.innerHTML='<iframe name="'+n+'" src="about:blank" onload="this.onload_callback()"></iframe>';var i=c.childNodes[0];i.onload_callback=
function(){var a=e.createElement("form");c.appendChild(a);a.method="post";a.enctype="multipart/form-data";a.encoding="multipart/form-data";if(d.target){a.target=d.target;a.setAttribute("target",d.target)}else{a.target=n;a.setAttribute("target",n)}a.action=d.action;a.setAttribute("action",d.action);a.style.margin=0;a.style.padding=0;a.style.height="80px";a.style.width="40px";a.runat="server";var j=d.action_params;for(var p in j){var m=e.createElement("input");m.type="hidden";m.name=p;m.value=String(j[p]);
a.appendChild(m)}if(d.maxsize){j=e.createElement("input");j.type="hidden";j.name="MAX_FILE_SIZE";j.value=String(d.maxsize);a.appendChild(j)}b=e.createElement("input");b.name=d.dataname;b.type="file";b.size="1";b.runat="server";a.appendChild(b);b.style.position="absolute";b.style.display="block";b.style.top=0;b.style.left=0;b.style.height=a.style.height;b.style.width="80px";b.style.opacity=0;b.style.filter="alpha(opacity=0)";b.style.fontSize=8;b.style.zIndex=1;b.style.visiblity="hidden";b.style.marginLeft=
"-40px";var o=function(){if(b.value){var f=d.onstart;f&&f(b.value);a.submit()}};if(b.addEventListener)b.addEventListener("change",o,false);else if(b.attachEvent)b.attachEvent("onpropertychange",function(f){if(!f)f=window.event;f.propertyName=="value"&&o()});else b.onpropertychange=o;i.onload_callback=function(){var f=null;if(i.contentWindow)f=i.contentWindow;else if(i.contentDocument)f=i.contentDocument.defaultView;f=f.document.body.innerHTML;var q=d.oncomplete;q&&q(f);a.reset()}};i.style.display=
"none";i.width=0;i.height=0;i.marginHeight=0;i.marginWidth=0;e.body.insertBefore(c,e.body.firstChild);c.style.position="absolute";c.style.overflow="hidden";c.style.padding=0;c.style.margin=0;c.style.visiblity="hidden";c.style.width="0px";c.style.height="0px";if(d.zindex=="auto"){g=0;var l;for(h=k;h.tagName!="BODY";){l=h.currentStyle?h.currentStyle:getComputedStyle(h,null);l=parseInt(l.zIndex);l=isNaN(l)?0:l;g+=l+1;h=h.parentNode}c.style.zIndex=g}else c.style.zIndex=d.zindex;g=function(a){if(!a)a=
window.event;c.style.width="0px";c.style.height="0px";if(e.elementFromPoint(a.clientX,a.clientY)===k){c.style.width="40px";c.style.height="80px"}};if(c.addEventListener)c.addEventListener("mousemove",g,false);else c.attachEvent&&c.attachEvent("onmousemove",g);g=function(a){if(!a)a=window.event;var j=y=0;if(a.pageX)j=a.pageX;else if(a.clientX)j=a.clientX+(e.documentElement.scrollLeft?e.documentElement.scrollLeft:e.body.scrollLeft);if(a.pageY)y=a.pageY;else if(a.clientY)y=a.clientY+(e.documentElement.scrollTop?
e.documentElement.scrollTop:e.body.scrollTop);c.style.left=j-20+"px";c.style.top=y-40+"px";c.style.width="40px";c.style.height="80px"};if(k.addEventListener)k.addEventListener("mousemove",g,false);else k.attachEvent&&k.attachEvent("onmousemove",g)};

来源。观看视频以了解其工作原理 ^^ http://www.fabiobiondi.com/blog/2012/10/upload-images-from-the-user-hard-driveto-an-html5-canvas-easel-js-应用/

于 2013-12-04T19:42:34.517 回答