当前位置:   article > 正文

uni-app使用canvas层级过高解决方案_uniapp canvas层级太高

uniapp canvas层级太高
  • 效果图

在这里插入图片描述

  • 解决方法

    在canvas画完图后,使用uni.canvasToTempFilePath生成本地图进行展示
    注意:生成图片的时候用setTimeout延迟一下,否则生成的图片会为空
  • 代码

<template v-if="!cpbarCanvasImg && !cpbgCanvasImg">
	<canvas class="progress_bg" canvas-id="cpbg"></canvas>
	<canvas class="progress_bar" canvas-id="cpbar"></canvas>
</template>
<template v-if="cpbarCanvasImg && cpbgCanvasImg">
	<image class="progress_bg" :src="cpbgCanvasImg" mode=""></image>
	<image class="progress_bar" :src="cpbarCanvasImg" mode=""></image>
</template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

第一个圆

drawProgressbg: function() {
// 自定义组件实例 this ,表示在这个自定义组件下查找拥有 canvas-id 的 <canvas/>
	var ctx = uni.createCanvasContext('cpbg', this);
	ctx.setLineWidth(12); // 设置圆环的宽度
	ctx.setStrokeStyle('#F5F5F5'); // 设置圆环的颜色
	ctx.setLineCap('round'); // 设置圆环端点的形状
	ctx.beginPath(); //开始一个新的路径
	ctx.arc(56, 60, 50, Math.PI, 2 * Math.PI, false);
	//设置一个原点(110,110),半径为100的圆的路径到当前路径
	ctx.stroke(); //对当前路径进行描边
	ctx.draw();
	
	let that = this
	setTimeout(() => {
		uni.canvasToTempFilePath({
			canvasId: 'cpbg',
			success: function(res) {
				console.log('res1', res)
				that.cpbgCanvasImg = res.tempFilePath
			}
		},that)
	},500)
},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

第二个圆

drawCircle: function(step, total) {
	var ctx = uni.createCanvasContext('cpbar', this);
	ctx.setStrokeStyle('#4C77F4');
	ctx.setLineWidth(12);
	ctx.setLineCap('round');
	ctx.beginPath();
	// 参数step 为绘制的百分比
	step = (step / total) + 1;
	if (step >= 2) {
		step = step % 2;
	}
	
	ctx.arc(56, 60, 50, Math.PI, step * Math.PI, false);
	ctx.stroke();
	ctx.draw();
	
	let that = this 
	setTimeout(() => {
		uni.canvasToTempFilePath({
			canvasId: 'cpbar',
			success: function(res) {
				console.log('res2', res)
				that.cpbarCanvasImg = res.tempFilePath
			}
		},that)
	},500)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/741698
推荐阅读
相关标签