所以我试图在引导弹出窗口内渲染图表,但它似乎没有渲染。我已经尝试了所有可能的方法来调试,但我无法完全弄清楚出了什么问题。因此,任何帮助将不胜感激。下面是我的html代码:
<div id="popover-content" style="display: none;">
{%include 'scroll_card.html'%}
</div>
注意:我正在使用 jinja 来渲染我的 html 代码,其中包含我想在弹出窗口中显示的图表。以下是scroll_card.html 文件中的内容
<div class='summary'><h5 class='header'> Chart </h5>
<div class="chart" style="height: 400px;">
<canvas id='hourly-chart' width="300" height="400">Hello</canvas></div>
</div>
还有我的js代码:
document.addEventListener('DOMContentLoaded', function() {
const myPopoverTrigger = document.getElementById('popover');
let hourChart =null;
const instance = new mdb.Popover(myPopoverTrigger, {
title:"Hourly Forecast",
sanitize:false,
html:true,
content: function(){
popContent = document.querySelector('#popover-content').innerHTML;
return popContent;
}
});
myPopoverTrigger.addEventListener('show.mdb.popover', () => {
const ctxHour = document.getElementById('hourly-chart').getContext('2d');
console.log(ctxHour);
if (hourChart) {
hourChart.destroy();
}
hourChart = new Chart(ctxHour, {
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
responsive: false,
scales: {
y: {
beginAtZero: true
}
}
}
});
console.log(hourChart);
});
myPopoverTrigger.addEventListener('hide.mdb.popover', () => {
if (hourChart) {
hourChart.destroy();
}
});
});
另一个注意事项:当我使用 console.log 图表(hourChart)时,它在控制台中返回一个图表对象,该对象提供了一些奇怪的属性,例如在选项中,它返回 x 和 y 为未定义。我可能做错了什么或遗漏了什么吗?
谢谢
HTML 内容应直接在选项中提供。否则,它不会及时添加到 DOM 中以供画布/图表渲染。
const instance = new mdb.Popover(myPopoverTrigger, {
title: "Hourly Forecast",
sanitize: false,
html: true,
content: `<div id="popover-content">
<div class='summary'>
<h5 class='header'> Chart </h5>
<div class="chart" style="height: 400px; width: 600px;">
<canvas id='hourly-chart' width="600" height="400"></canvas>
</div>
</div>
</div>`
});