Small program Huawei mobile phone canvas does not display the problem

On some Huawei mobile phones, the WeChat applet does not display the drawn content on the canvas

1. First upload the code, it is very simple, first download the picture from the website to generate a temporary path, and then draw the picture back, the test uses a P30 device, the phenomenon is that nothing is displayed, and there is no error in the log log in the debug mode

wx.getImageInfo({
    
    
	src: "http://mb-yun.oss-cn-hangzhou.aliyuncs.com/elinglishtalk/images/work_save_success.png", //网络图片路径
	success: res => {
    
    
		this.canvasWork(res.path)
	}
})

canvasWork: function(imagePath) {
    
    
	//获取学生名称
	let userName = "用户名"
	let ctx = wx.createCanvasContext('myCanvas');
	let W = 350;
	ctx.rect(0, 0, W, 568)
	ctx.setFillStyle('#fff')
	ctx.fill()
	ctx.clip();

	ctx.drawImage(imagePath, 135, 250, 80, 80, 0, 0)
	ctx.draw()
	ctx.beginPath()

	ctx.setFontSize(25);
	ctx.setFillStyle('#565656');

	let title = "作业打卡"

	ctx.fillText(title, (W - ctx.measureText(title).width) * 0.5, 100, 300);
	ctx.setFontSize(20);
	ctx.fillText(userName, (W - ctx.measureText(userName).width) * 0.5, 150, 300);
	ctx.draw(true);
},

2. At first I thought it was caused by the fact that getImageInfo failed to download the image successfully, so I typed the log and found that the temporary path of the callback was fine. Later, I directly removed the getImageInfo method and replaced it with a local image, but there are still problems after testing, so I ruled it out The problem with getImageInfo

ctx.drawImage("../../images/work_save_success.png", 135, 250, 80, 80,0,0)

3. I went to the WeChat development community and searched for a long time and found similar problems. The solution is to go to the small program open community after a delay

setTimeout(()=>{
    
    
  this.canvasWork()
},2000)

It seems that there is only one way to solve it at present. To be on the safe side, the delay is 2s, and some mobile phones may not work for 1s.

Points to note when using canvas

1. If the canvas is in a custom component, you need to pass in this when creatingCanvasContext

wx.createCanvasContext('myCanvas',this);

2. When using the drawImage method of CanvasContext, if you are drawing a network image, you need to download it first through getImageInfo / downloadFile. 3. Canvas
gets the width of the drawn text and the unit is px. If it involves the centering of the drawn text content, you need to calculate the left and right spacing. , you need to pay attention to whether the unit you set in wxml is px or rpx, and pay attention to the conversion of the unit

Guess you like

Origin blog.csdn.net/qq_36356379/article/details/107915659