0

I have two div's :

<div id="div_h">
    <canvas class="canvas" width="570" height="428" id="myCanvas"></canvas>
</div>


<div  id="div_p">
    <canvas class="canvas" width="828" height="528" id="canvas"  ></canvas>
</div>

I have a button that change the content of these div's:

$('#finish').click(function() {

                $el_div_h = $('#div_h');
                $el_div_p = $('#div_p');

                $div_h      = $el_div_h.html();
                $div_p  = $el_div_p.html();

                $el_div_h.empty();
                $el_div_p.empty();

                $el_div_h.html($div_p);
                $el_div_p.html($div_h);

            });

but when I click on finish button, canvas changed to white color. content of my canvas is two different images.

S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • So, you want to swap the canvases from div_p to div_h and vice versa? – Doug Mar 08 '18 at 13:30
  • yes.I want to swap two canvas. – S.M_Emamian Mar 08 '18 at 13:32
  • you'll need to rerun the code for instantiating whatever is in the canvas. the canvas elements will be completely new dom elements after this. – GNi33 Mar 08 '18 at 13:35
  • just swapping the position of the divs using CSS would be a much easier and more performant solution – GNi33 Mar 08 '18 at 13:36
  • https://stackoverflow.com/questions/7242006/html5-copy-a-canvas-to-image-and-back what about drawing the content of one canvas to another? (you may need a hidden-dummy canvas to shuffle the images around) – Doug Mar 08 '18 at 13:37
  • This is duplicate question. Similar question is already there, https://stackoverflow.com/questions/17278913/swapping-div-with-canvas-elements-using-javascript Please verify before posting question. – Nitin Kothwal Mar 08 '18 at 13:50

1 Answers1

2

You can use something like this:

$('#finish').click(function() {
    var elms1 = $('#div_h').children().detach();
    var elms2 = $('#div_p').children().detach();
    $('#div_h').append(elms2);
    $('#div_p').append(elms1);
    console.log($('#div_h').find("canvas").attr("id"));
    console.log($('#div_p').find("canvas").attr("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="finish">FINISH</button>
<div id="div_h">
    <canvas class="canvas" width="570" height="428" id="myCanvas"></canvas>
</div>
<div  id="div_p">
    <canvas class="canvas" width="828" height="528" id="canvas"  ></canvas>
</div>

This will keep the <canvas>es intact because you're not storing the <div>s' HTML code, you're storing the child elements of those containers.

Titus
  • 22,031
  • 1
  • 23
  • 33