html2canvas turn pictures encountered pit (picture offset, blur images, font changes)

Share page recently made a request to save the album press, which uses a html2canvas, using relatively simple, but the more common a few pit encountered, do the next summary:

1. solve fuzzy pictures and offset

$ ( '. Share') is required to turn the picture dom

function share() {
		var width = $('.share')[0].offsetWidth; //dom宽
		var height = $('.share')[0].offsetHeight; //dom高
		// 解决图片模糊
		var scale = 2;//放大倍数
		var canvas = document.createElement('canvas');
		canvas.width = width * 2;
		canvas.height = height * 2;
		canvas.style.width = width + 'px';
		canvas.style.height = height + 'px';
		var context = canvas.getContext('2d');
		context.scale(scale, scale);
                //设置context位置,值为相对于视窗的偏移量负值,让图片复位(解决偏移的重点)
                var rect = $('.share').get(0).getBoundingClientRect();//获取元素相对于视察的偏移量
		context.translate(-rect.left, -rect.top);

		var opts = {
			canvas: canvas,
			useCORS: true, // 【重要】开启跨域配置
			scrollY: 0, // 纵向偏移量 写死0 可以避免滚动造成偶尔偏移的现象
		};
		html2canvas($(".share")[0], opts).then(canvas => {
			// 使用toDataURL方法将图像转换被base64编码的URL字符串
			var src = canvas.toDataURL();
			// 显示图片隐藏dom(图片生成后的操作)
			$('.share-wrap').addClass('hidden');
			$('.share-canvas').removeClass('hidden');
			$('.share-canvas').find('img').attr('src', src);
		});
	}

When the query data, also found an obscure action: Use the background image, so it is necessary that all images into foreground img

NOTE: Use vant assembly will pop deviated animation; generating units of picture elements employed px

2. troubleshoot font changes:

Projects need to use bold, direct set font-family: "SimHei"; not afford to do with the time, and occasionally see an article learned canvas transfer operation of the font, use your browser to open the page, the browser reads the HTML file parsing rendering for html text will be converted into the corresponding unicode code, and then (if not set, use the default browser settings) in accordance font-family HTML settings to find the computer (custom fonts @ font- if face, then load the corresponding font file) corresponding to the font of font file, find the file to find the shape drawn based on unicode code found after the draw onto the page.

Solution: font-family: "\ 9ED1 \ 4F53"; (converted to unicode font code display)

 

Published 32 original articles · won praise 11 · views 110 000 +

Guess you like

Origin blog.csdn.net/jinxi1112/article/details/101285998