首页 > 解决方案 > 没有调整视口大小的动画后画布不渲染

问题描述

我有两个 div,每个 div 包含一个画布。在初始状态下,只显示一个,另一个显示设置为无。单击第一个画布后,将执行此代码:

$("#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"});
    }
});

动画按预期工作,但未显示画布。它仅在调整视口大小后出现。为什么会这样,我该如何解决?

我正在使用chart.js。

标签: javascriptcanvaschart.js

解决方案


当图表变得可见时,您可以尝试调用图表.update() 查看更新文档。#graphTwo(因为,当您调整视口大小时会发生这种情况 -> 更新图表)

...
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
}
...

但是您应该小心响应页面文档中的此通知:

重要说明无法直接从画布元素检测画布大小何时更改。Chart.js 使用其父容器来更新画布渲染和显示大小。

我认为如果父级不可见,则启动或更新图表,那么稍后渲染图表可能会遇到问题。因此,也许最安全的方法是在动画完成后更新图表。

...
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"); // ?      
}
...

这有什么不同吗?


推荐阅读