3

I am trying to add multiple images to Html5 canvas but every time I try to remove the last image and show the most recent one it fails. Here's my code:

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

If I run this code, it shows the 2nd image on the canvas and removes the first one. Is there any way to retain both the images?

2
  • Looks like you're just overwriting the first one with the second one, since you're writing them both at 0,0. Is the first one smaller than the second one? Commented Jun 27, 2012 at 13:23
  • i have even tried changing the co-ordinates but no help there either, no the second one is smaller Commented Jun 27, 2012 at 13:24

2 Answers 2

5

Actually onLoad always uses last value of the variables. So store (calculate) img x, y coordinates before. Smth like this:

imageObj.setAtX = i * 10;
imageObj.setAtY = i * 10;
imageObj.onload = function() {
     context.drawImage(this, this.setAtX, this.setAtY);
};
Sign up to request clarification or add additional context in comments.

4 Comments

is there any documentation why "onload" has this behaviour? its feels unusual to me...
... additionally: dont try imageObj.x .. it seems to be reserved
@wutzebaer the onload here only allows one to bind some anonymous function to a state in the image lifecycle, such that when the image finishes loading, a function is called. The reference of this inside that anonymous function is the image that loaded...
This works! This is an Excellent and Concise Answer.
-1

I've tried it with easeljs. This might help you.

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

The source. Watch the video to see how it works ^^ http://www.fabiobiondi.com/blog/2012/10/upload-images-from-the-user-hard-driveto-an-html5-canvas-easel-js-application/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.