Hi,
I am using chart js and chart plugin in template node to implement the chart, I found the zoom feature is normal while the pan feature is not available. And I tried several ways to change the settings in plugin, it did not work.
And the Mouse dwon/up event can be captured by document.getElementById('myChart'), but the pan feature is still not working.
Here is my code, any idea about this problem? I am using dashboard2.0 @flowfuse/node-red-dashboard 1.26.0
<!-- 容器用于渲染图表 -->
<div style="width:100%; height:300px;">
<canvas id="myChart"
pointer-events: auto></canvas>
</div>
<!-- 引入 Chart.js 及其缩放插件 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2.0.1"></script>
<!-- 初始化图表 -->
<script>
Chart.register(ChartZoom);
// 获取 Canvas 上下文
const ctx = document.getElementById('myChart').getContext('2d');
const canvas = document.getElementById('myChart');
['mousedown', 'mouseup'].forEach(event => {
canvas.addEventListener(event, (e) => {
console.log(`Mouse dwon/up event: ${event} at (${e.clientX}, ${e.clientY})`);
e.stopPropagation();
});
});
// 初始化数据(默认值,可通过 msg 动态更新)
let chartData = {
datasets: [{
label: 'Sample Data',
data: [{ x: 1, y: 5 }, // 第一个点 (X=1, Y=5)
{ x: 2, y: 10 },
{ x: 3.5, y: 6 },
{ x: 4, y: 2 },
{ x: 3, y: 8 }],
borderColor: 'rgb(75, 192, 192)',
showLine: true,
tension: 0.1
}]
};
// 创建图表
const myChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
interaction: {
mode: 'nearest', // 关键:不让 tooltip 抢事件
intersect: false// 避免鼠标事件冲突
},
scales: {
x: {
type: 'linear', // X 轴为线性轴(适用于数值型数据)
position: 'bottom'
},
y: {
type: 'linear' // Y 轴为线性轴
}
},
plugins: {
zoom: {
pan: {
enabled: true, // 启用拖动平移
mode: 'xy', // 同时平移 X 和 Y 轴
modifierKey: null, // 不需要按键直接拖动
onPanStart({chart}) { console.log('paning'); },
onPan({chart}) { console.log('paning'); },
threshold: 1// 拖动距离阈值,防止误触
},
zoom: {
wheel: { enabled: true }, // 启用滚轮缩放
pinch: { enabled: true }, // 启用 pinch 缩放(触摸设备)
mode: 'xy' , // 同时缩放 X 和 Y 轴
drag: { enabled: false } // 关闭框选缩放
}
}
}
}
});
</script>