neoahead
neoahead

Reputation: 265

multiple canvas at same location using javascript

I am trying to make a application one of the module is displaying a multiple canvas at same location. This canvas is used to display graph. I have 2 buttons: pie and bar:

When I click on pie it should display pie chart. and when I click on bar it should display bar graph. I am using following approach:

  1. rendering 2 canvas at same location.

    .wrapper canvas {
        position: absolute;
        top: 0px;
        left: 0px;
        visibility:hidden;
    }
    
  2. In pie button i'm hiding bar chart and display pie. Same goes for bar button.

    $("input[type='radio']").change(function(){
      var  whChart = $('input[name="radio-view"]:checked').val();
      var canpie = document.getElementById('pie4');//$("canvas[name='pie4'][0]");
      var canbar = document.getElementById('pie41');//$("canvas[name='pie4'][0]");
      if(whChart == "Pie"){
          RGraph.Effects.jQuery.Snap(pie4);
          canpie.style.visibility='visible';
          canbar.style.visibility='hidden';
      }
      else if( whChart == "Bar"){
            RGraph.Effects.jQuery.Snap(pie41);
            canpie.style.visibility='hidden';
            canbar.style.visibility='visible';
      }
    });
    

html file

<div class="wrapper" style="text-align:center;">
    <canvas id="pie4" width="450" height="250" style="background:black;  z-index: 1; visibility:visible; ">[No canvas support]</canvas>
    <canvas id="pie41" width="450" height="250" style="background:red;  z-index: 2;">[No canvas support]</canvas>
</div>

But the problem is these 2 canvas are displaying one below another. Not at the same place overlapping.

I have checked other post related to double buffering and also tried other options like making 1st canvas height and width to '0', but it doesn't seems to work. Could please someone help in this matter. Since I'm very new to this JavaScript.

p.s : Sorry this is my first post. I know there are lot of mistakes and information missing. If you let me know if anything else needed I will provide.

Upvotes: 1

Views: 2057

Answers (1)

epascarello
epascarello

Reputation: 207511

The problem is visibility keeps the space, you want to use display which does not maintain the space.

var pieState = (whChart == "Pie") ? "block" : "none"; 
var barState = (whChart == "Bar") ? "block" : "none"; 
canpie.style.display = pieState;
canbar.style.display = barState;

Please see this stackoverflow question for an explanation.

Since you seem to be using jQuery, you could just use jQuery's show()/hide() or toggle()

Upvotes: 2

Related Questions