how do i toggle visibility between 2 canvas using html / css / js /?

10,257

Here's one way to use a button to toggle visibility of 2 canvases so that only 1 canvas is visible:

  • use CSS to stack the 2 canvases on top of each other inside a wrapper div using positioning.

  • Toggle the style.visibility of the 2 canvases in response to your button click.

Here's an example:

var canvas1=document.getElementById('canvas1');
canvas1.getContext('2d').fillText('This is canvas1',20,20);
var canvas2=document.getElementById('canvas2');
canvas2.getContext('2d').fillText('This is canvas2',20,20);

swapCanvases();

document.getElementById("test").onclick=function(){
  swapCanvases();
};

function swapCanvases(){
  if(canvas1.style.visibility=='visible'){
    canvas1.style.visibility='hidden';
    canvas2.style.visibility='visible';
  }else{
    canvas1.style.visibility='visible';
    canvas2.style.visibility='hidden';
  }
}
body{ background-color: ivory;}
#wrapper{position:relative;}
#canvas1{position:absolute; border:1px solid red;}
#canvas2{position:absolute; border:1px solid blue;}
<button id="test">Swap Canvas Visibilities</button>
<div id=wrapper>
  <canvas id="canvas1" width=300 height=300></canvas>
  <canvas id="canvas2" width=300 height=300></canvas>
</div>

Share:
10,257
SeeSharp
Author by

SeeSharp

Updated on June 07, 2022

Comments

  • SeeSharp
    SeeSharp almost 2 years

    dear stackoverflowers

    I have 2 canvases:

    1. A canvas to show presentations,
    2. And a second hidden canvas to create presentations.

    I need to switch which canvas is visible with a single button click

    </div>
            <canvas id="myCanvas" width="800" height="600" style="border:1px solid #000000;" hidden="outputcanvas">
            </canvas>    
    </div>
    
    <!----------------------------------------------------------------------------------------------------------------------------------------------------->
    <!-- input canvas -->
        <div>
            <canvas width="800" height="600" hidden="inputcanvas" ></canvas>
        </div>
    

    is it possible ? if so , how ?

    at this moment i trying to solve it with JS ^^

    thanks in advance