需求:绘制展示缺货量,缺品情况的百分比圆环
<canvas canvas-id="myCanvas" class="canvas"></canvas>
<!-- canvas绘制的图片 -->
<image :src="item.tempFilePath" class="item-img" mode="aspectFill"></image>
绘制画布
/**
* @stock_out_rate 缺货百分率
* @stock_out_rate_int 缺货率数值
*/
initCanvas(item) {
let newVal = item.stock_out_rate //显示缺货率百分比
let val = item.stock_out_rate_int<0 ? 0 : parseFloat(Math.abs(item.stock_out_rate_int) /100).toFixed(2)
const ctx = uni.createCanvasContext('myCanvas',this); //拿到canvas对象(自己的定义的canvas-id)
ctx.beginPath(); // 开始绘制路径
ctx.arc(25, 25, 20, 0, 2 * Math.PI); // arc画圆
ctx.setStrokeStyle("#f2f2f2");
ctx.setLineWidth(3); // 线条宽度
ctx.stroke(); // 绘制成线条(fill()是填充为饼图)
// 开始绘制第二条路径 缺货率 橘色
ctx.beginPath();
ctx.arc(25, 25, 20, 0, val * 2 * Math.PI,false);
if(item.stock_out_rate_int==0 || item.stock_out_rate_int< 50) {//满柜
ctx.setStrokeStyle("#007AFF"); //缺货率小于50为蓝色
}else {
ctx.setStrokeStyle("#f95454"); //缺货率大于50为红色
}
ctx.setLineWidth(3);
ctx.stroke();
// 填充字体-367
ctx.setFillStyle("#333");
ctx.setFontSize(12);
ctx.setTextAlign("center");
ctx.fillText(newVal, 25, 30);
ctx.stroke();
ctx.draw()
}
*注意:canvas不能和scroll-view一起使用,同时使用会出现画布抖动问题*
解决canvas抖动问题
1. uni.canvasToTempFilePath()方法生成图片
2. 在页面中隐藏canvas,使用图片展示画布绘制样式
.canvas {
position: fixed;
right: 100%;
}
.item-img {
width: 100rpx;
height: 100rpx;
}
3. 获取canvas绘制的图片
// canvas画布绘制图片不显示,使用setTimeout()延迟绘制解决
let timer = setTimeout(() => {
ctx.draw(false, () => {
uni.canvasToTempFilePath({
width: 50,
height: 50,
destWidth: 100,
destHeight: 100,
canvasId: item.id,
success: (res) => {
// 保存生成的图片路径
this.$set(item,'tempFilePath',res.tempFilePath)
clearTimeout(timer)
},
fail: (res) => {
console.log('fail',res)
}
})
})
},1000)