Draw same javascript object on different canvas

3

I created a standardized function to speed up the design process in a project that involves multiple canvases.

  

Thank you for the collaboration of bfavaretto link

See the function: (it works correctly)

var drawIt = function (canvasCtx, drawObj, x, y) {
    drawObj.onload = function () {
        canvasCtx.drawImage(drawObj, x, y);
    };
};

I called the various canvases in the script: (and were initialized correctly):

var c1Canvas = document.getElementById("c1");
var c1Ctx = c1Canvas.getContext("2d");

var c2Canvas = document.getElementById("c2");
var c2Ctx = c2Canvas.getContext("2d");

var c3Canvas = document.getElementById("c3");
var c3Ctx = c3Canvas.getContext("2d");

var c4Canvas = document.getElementById("c4");
var c4Ctx = c4Canvas.getContext("2d");

See HTML5 snippet:

<div class="gfwrapper">
    <canvas id="c1" width="800" height="600"></canvas>
    <canvas id="c2" width="800" height="600"></canvas>
    <canvas id="c3" width="800" height="600"></canvas>
    <canvas id="c4" width="800" height="600"></canvas>
</div>

And from this point I created objects for the images that should be added to Canvas:

var image1 = new Image();
image1.src = "http://folhaz.com.br/cms/wp-content/uploads/2014/02/carnaval-300x237.jpg";

var image2 = new Image();
image2.src = "https://www.google.com.br/images/srpr/logo11w.png";

var image3 = new Image();
image3.src = "http://folhaz.com.br/cms/wp-content/uploads/2012/10/sky-tv.jpg";

var image4 = new Image();
image4.src = "http://folhaz.com.br/cms/wp-content/uploads/2013/12/web300x180px1.jpg";

However, to my surprise, I can not add the same image object to different canvases.

See the code below.

function drawScreen() {
    drawIt(c1Ctx, image1, 0, 0);
    drawIt(c2Ctx, image2, 0, 0);
    drawIt(c3Ctx, image3, 0, 0);
    drawIt(c4Ctx, image4, 0, 0);

    drawIt(c4Ctx, image1,100,100);
}

drawScreen();

Image1 was initially added to c1. When trying to add it to c4, image1 is deleted from c1 and drawn at c4. I would like the image to be kept in c1, without renaming the object.

Does anyone know a workaround for this? Is it possible?

Follow JSFiddle to help: link

    
asked by anonymous 04.03.2014 / 17:12

1 answer

5

You need a separate object for the image (do not worry, it will be loaded from the cache):

var image5 = new Image();
image5.src = "http://folhaz.com.br/cms/wp-content/uploads/2014/02/carnaval-300x237.jpg";

// ...

drawIt(c4Ctx, image5, 100, 100);

An alternative is to clone the image before passing it to the function:

drawIt(c4Ctx, image1.cloneNode(), 100, 100);
    
04.03.2014 / 17:28