html2canvas usage record

The plug-in, I use version 1.0.0-rc.4, some of the problems of the old version mentioned on the Internet have basically been solved, such as the blurring of screenshots on the mobile phone and the problem of cross-domain image caching, but none of them appeared.

note

1. When taking a screenshot of content whose height is higher than the window, make sure that the scroll bar is at the top, otherwise there will be a blank at the top of the captured image.
2. In the local test, if the image is a local image, you need to access this page through a URL. If you open the html file directly, an error is reported:Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported

//此处dom对象也可使用jquery获取,但要注意jquery获取的是jqery对象obj;obj[0]才是dom对象
var dom = document.getElementById('big_div');
//html2canvas代码
html2canvas(dom,{
    
    
	/*
	允许读取跨域图片
	此处设置可读取跨域图片,是给dom中的图片添加了crossorigin="anonymous"属性,作用是使canvas在渲染图片时,http请求头中发送了跨域请求。
	网上有朋友说,在dom加载进canvas之前,浏览器会缓存图片信息,包括响应头。
	当canvas渲染dom时,img设置了crossorigin="anonymous"属性,但因为一开始页面的图片没有设置crossorigin属性,缓存的图片并没有保存Access-Control-Allow-Origin跨域信息。
	此时dom中的img以跨域的方式请求图片时,读取的是缓存中的图片信息,因为获取不到Access-Control-Allow-Origin,所以加载失败。
	在页面中,把所有图片加上crossorigin属性,可避免出现该情况。针对已生成缓存的用户,可在图片后追加字符串,生成新的缓存图片。
	但我在使用中,暂时没有出现这种情况,只需设置useCORS后就能正常截图
	这里记录一下,以后如果碰到可做相应修改
	*/
    useCORS: true,
    //设置canvas宽高,其实没什么用
    //设置后,canvas宽高虽然变了,但截取的dom的宽高是不会变的
    //相当于截取了dom的一小块儿内容
    //在PC端,当我们设置了dom的宽高时,生成的图片是和我们设置的宽高一致的
    //在移动端时,dom的宽高无效,插件会自动把生成的图片放大,保证了清晰度
    width:200,
    height:600,
})
    .then(function(canvas){
    
    
        var img = new Image();
        img.setAttribute('src', canvas.toDataURL('image/png'));
		$('#big_div').html(img);
    });

Guess you like

Origin blog.csdn.net/u012830303/article/details/107312580