html2canvas cross-domain stepping pit daily

In the past two days, I received instructions from the company to share posters and then tried to use html2canvas+uview+uniapp to write

Step on the pit as follows

  1. html2canvas cross-domain problem
    Our company uses oss cloud storage. At first, the cross-domain occurred because of local reasons, so I didn’t care about it.
    When it was deployed to the test server the next day, the cross-domain still occurred, so I started to pay attention. The investigation is
    as follows:
  • Check whether the oss cloud storage is set to cross-domain (already set)
  • Check whether html2canvas has set useCORS to true (already set)

After the inspection, I found that there was no problem, so I fell into contemplation. I didn’t solve it from the morning until the afternoon. I had no choice but to try to convert the image to base64, but I didn’t find a suitable conversion method under uniapp. Most of them were generated canvas to base64. ... So I decided to write an interface on the back end to convert base64, and then use html2canvas to generate it after conversion

The canvas generation code is as follows

	// html2canvas生成画布代码
	let container = document.getElementById('shareModal')
	html2canvas(container, {
    
    
		scale: 2,
		backgroundColor: '#fff',
		useCORS: true,
	}).then(canvas => {
    
    
		this.canvasUrl = canvas.toDataURL("image/png");
		uni.showToast({
    
    
			icon: 'success',
			title: '生成图片成功,长按图片可进行保存哦'
		})
	})
  1. The conversion was successful. When I tried to replace the avatar with base64, strange things happened again. After the generation, there was still no avatar. Check that the data has been assigned and then debug the page.

insert image description here

I found that the uniapp image component used will set a background-image attribute by default. When I replaced the value of avatar with base64, the background-image attribute did not change

Solution: After getting the data, assign it to a temporary variable first, and then assign it to data after changing the avatar value of the temporary variable

The complete code is as follows

this.$u.api.getUserInfo({
    
    }).then(res => {
    
    
		if (res.code != 1) {
    
    
			this.$u.toast('获取用户信息失败')
		}		
		let userinfo = res.data
		if (userinfo.avatar){
    
    
			if (!userinfo.avatar.indexOf('data:image') >= 0){
    
    
				this.getBase64(userinfo.avatar).then(data => {
    
    
					// TODO: 注意  此处需要将\r\n换行替换为空,不然无法显示
					userinfo.avatar = data.data.replace(/[\r\n]/g, '')
					that.userinfo = userinfo
				})
			}
		}
});

The renderings are as follows
insert image description here

Summary:
The two problems encountered only figured out the solution
and did not find out the reason. If anyone knows, please let me know!

Guess you like

Origin blog.csdn.net/Quiet_tomcat/article/details/123073335