const echarts = require('../../static/libs/echarts.js');
Component({
properties: {
canvasId: {
type: String,
value: 'myChartCanvas'
},
ec: {
type: Object,
value: null
}
},
data: {
isInit: false
},
methods: {
init(callback) {
console.log(`🔍 开始初始化 Canvas (canvas-id: ${this.data.canvasId})`);
const query = this.createSelectorQuery().in(this);
setTimeout(() => {
query.select('canvas').fields({
node: true,
size: true
}).exec((res) => {
const result = res && res[0];
if (!result || !result.node) {
console.error('❌ 未获取到 canvas 节点,请确认以下几点:');
console.error(' 1. 微信基础库版本 >= 2.14.0');
console.error(' 2. <canvas> 标签存在于 wxml 中且未被隐藏');
console.error(' 3. 项目已清除缓存并重启开发者工具');
console.error(' 4. ec-canvas 容器有明确高度(如 height: 300px)');
return;
}
const canvas = result.node;
const width = result.width;
const height = result.height;
if (width <= 0 || height <= 0) {
console.error(`❌ canvas 尺寸异常:width=${width}, height=${height}`);
console.warn('💡 请确保父容器设置了固定高度,例如 style="height: 300px;"');
return;
}
const dpr = wx.getSystemInfoSync().pixelRatio || 2;
canvas.width = width * dpr;
canvas.height = height * dpr;
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('❌ 无法获取 Canvas 2D 上下文');
return;
}
const chart = echarts.init(ctx, null, {
width: width,
height: height,
devicePixelRatio: dpr
});
this.chart = chart;
console.log(`✅ ECharts 初始化成功!尺寸: ${width}x${height}, DPR: ${dpr}`);
if (typeof callback === 'function') {
callback(chart, width, height, dpr);
} else {
console.warn('⚠️ init 被调用但未传入回调函数');
}
});
}, 50);
},
dispose() {
if (this.chart) {
this.chart.dispose();
this.chart = null;
console.log('🗑️ ECharts 实例已销毁');
}
}
},
ready() {
console.log('🟢 ec-canvas 组件 ready,开始初始化');
if (this.data.ec && typeof this.data.ec.init === 'function') {
console.log('🔄 检测到 ec.init,开始自动初始化');
this.init(this.data.ec.init);
} else {
console.log('ℹ️ 未配置 ec.init,等待外部手动调用 init()');
}
},
onError(e) {
console.error('❌ Canvas 错误:', e.detail);
},
detached() {
this.dispose();
}
});