简体   繁体   中英

Canvas not rendering after animation without resizing viewport

I have two divs containing one canvas each. In the initial state only one is being displayed, the other has display set to none. Upon clicking on the first canvas this code is executed:

$("#graph1").click(function(){
    if(!$("#graphTwo").hasClass("toggled")) {
        $("#graphTwo").animate({"height": "350px"}).removeClass("toggled");
        $("#graphTwo").animate({"width": "700px"});
    } else {
        $("#graphTwo").animate({"height": "0px"}).addClass("toggled");
        $("#graphTwo").animate({"width": "0px"});
    }
});

The animation works just as intended, but the canvas is not displayed. It only appear after resizing the viewport. Why is this and how can I fix it?

I'm using chart.js.

You could try to call for a chart .update() see docs on updates when the #graphTwo becomes visible. (Because, that's what happens when you resize the viewport -> update chart)

...
if(!$("#graphTwo").hasClass("toggled")) {
  $("#graphTwo").animate({"height": "350px"}).removeClass("toggled");
  $("#graphTwo").animate({"width": "700px"});
  /** add chart update here **/
  the_chart_2.update(); // --> put the Chart instance
}
...

But you should be careful at this notice from the Responsive page docs :

Important Note Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes.

I think that if the parent is not visible then the Chart is initiated, or updated, then you can have problems with rendering the chart later. So, maybe the safest way to do it is to update the chart, after the animation has finished .

...
if(!$("#graphTwo").hasClass("toggled")) {
  $("#graphTwo").animate({
    "height": "350px",
    "width": "700px"
  },
  500, /* speed */
  function(){
    // Animation ended
    /** add chart update here **/
    the_chart_2.update(); // --> put the Chart instance
  }).removeClass("toggled"); // ?      
}
...

Did this make a difference?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM