我们新建一个chart.js官网的最简单demo示例
<template>
<view class="content">
<canvas id="myChart"></canvas>
</view>
</template>
<script setup>
import Chart from 'chart.js/auto';
import { ref, onMounted } from 'vue';
onMounted(() => {
let ctx = document.getElementById('myChart');
// ctx = ctx.getElementsByClassName('uni-canvas-canvas')[0]
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}
]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
});
</script>
<style>
#myChart {
width: 100vw;
height: 400rpx;
}
</style>
在vue3中上述代码可以运行无报错,但是在小程序中会报错
Failed to create chart: can't acquire context from the given item
打印ctx发现是如下结构的虚拟dom
<uni-canvas canvas-id disable-scroll="false" id="myChart">
<canvas class="uni-canvas-canvas" width="300" height="150">
<div></div>
<uni-resize-sensor></uni-resize-sensor>
</uni-canvas>
猜测应该是uniapp为了兼容多端对canvas进行二次封装导致的报错,所以加了一行
ctx = ctx.getElementsByClassName('uni-canvas-canvas')[0]
保证new Chart的第一个入参一定是一个原汁原味的canvas标签的dom,问题解决。