在vue-cli中用法如下,先声明id为mychart的canvas,然后在F2中指向它,没有任何问题。
<canvas id="canvasId" height="200"></canvas>
this.myChart = new this.$F2.Chart({
id: "canvasId",
pixelRatio: window.devicePixelRatio,
padding: ["auto", "auto", "auto", "auto"]
});
但同样的写法,复制到uni-app中,会报如下错误。
回到uni-app官网查看发现canvas用法略有不同
发现canvas标签是包在uni-canvas里面的,所以在上面直接配置id为canvasId的时候,实际上是指不到内部的canvas这里的,指向的是外部的uni-canvas,所以就会报错。
解决思路一:通过获取uni-canvas下面实际的canvas标签,用el节点的方式传给F2。
<canvas canvas-id="canvasId" id="canvasId"></canvas>
var canvas = document.getElementById('canvasId').querySelector('canvas');
this.myChart = new this.$F2.Chart({
el: canvas,
pixelRatio: window.devicePixelRatio,
padding: ["auto", "auto", "auto", "auto"]
});
发现样式显示还是有点问题,也不太好调整。
解决思路二:自己通过js创建canvas标签,并插入到指定位置。
<div id="canvasId"></div>
var canvas = document.createElement('canvas');
canvas.style.width = "100%";
canvas.style.height = "250px";
document.getElementById('canvasId').appendChild(canvas);
this.myChart = new this.$F2.Chart({
el: canvas,
pixelRatio: window.devicePixelRatio,
padding: ["auto", "auto", "auto", "auto"]
});
再来看,发现已经达到了我们想要的效果,到此结束。