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

このコードを実行すると、キャンバスに2番目の画像が表示され、最初の画像が削除されます。両方の画像を保持する方法はありますか?

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

私はイーゼルでそれを試しました。これはあなたを助けるかもしれません。

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

アップロード/upload.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)};

起源。それがどのように機能するかについては、ビデオをご覧ください^^ 応用/

于 2013-12-04T19:42:34.517 に答える