能否用gridister.js实现c3.js图表响应式?组件调整时图表未同步
Fixing C3.js Chart Resizing with Gridster.js
Hey there! Let's get your C3.js charts resizing smoothly alongside your Gridster.js widgets. The code snippet you shared has a couple of key issues that are preventing the sync from working—let's break them down and fix things up.
What's Wrong with the Current Code?
- You're adding a new div instead of modifying the existing chart: Your code uses
d3.select("div#chart_donut").append("div"), which creates a new element instead of targeting the already-rendered C3 chart container. This won't affect the actual chart you want to resize. - You're not using C3's built-in resize method: C3 has a dedicated
resize()method designed for exactly this scenario—manually tweaking DOM elements with D3 bypasses C3's internal logic, leading to inconsistent behavior.
Corrected Implementation
Here's a revised version of your resize handler that should work as expected:
resize: { enabled: true, stop: function(event, ui, $widget) { // Get the updated Gridster widget dimensions var widgetData = this.serialize($widget)[0]; // Convert Gridster's row/column units to actual pixels var chartWidth = widgetData.size_x * this.options.colWidth; var chartHeight = widgetData.size_y * this.options.rowHeight; // Retrieve your C3 chart instance (better to store this when initializing!) // If you saved the instance on init: var myDonutChart = c3.generate({...}) var targetChart = c3.charts.find(chart => chart.element.id === 'chart_donut'); // Trigger the resize if we found the chart if (targetChart) { targetChart.resize({ width: chartWidth, height: chartHeight }); } } }
Key Notes to Make This Work
- Store your C3 chart instances: When you initialize your donut chart, save the instance to a variable (e.g.,
const myDonutChart = c3.generate({...})). This lets you skip thec3.charts.find()step and directly callmyDonutChart.resize(...)for better performance. - Double-check Gridster's unit conversion: Gridster's
size_xandsize_yare usually column/row counts, not pixel values. Multiply them bycolWidthandrowHeight(from your Gridster options) to get the actual pixel dimensions of the widget. - Avoid unnecessary DOM manipulation: Let C3 handle the resizing logic—its
resize()method will update the chart's internal layout, axes, and elements correctly without you having to manually adjust D3 elements.
Quick Test Tip
If you're still having trouble, add console.log(chartWidth, chartHeight) inside the resize handler to confirm you're getting the correct pixel values. If the numbers look off, double-check your Gridster colWidth and rowHeight settings.
内容的提问来源于stack exchange,提问作者Shahneel Ahmed
相关产品推荐
相关产品推荐

