当前位置: 首页 > Web前端 > HTML

html2canvas.js网页截图功能

时间:2023-04-02 13:49:12 HTML

需求:从网页生成一张图片,用户可以长按保存图片,然后分享到朋友圈。其中,图中二维码即可识别。(二维码太小会识别不出来)首先科普一下微信网页二维码识别的原理:截屏识别。当客户端发现用户在网页的img标签中进行长按操作时,会立即截屏并启动二维码识别算法。https://www.cnblogs.com/daipi...在官网发现html2canvas.js插件的一些bug:1.截图不完整,不完整解决方法://修改源码,添加自定义设置高度和宽度varwidth=options.width!=null?options.width:node.ownerDocument.defaultView.innerWidth;varheight=options.height!=null?options.height:node.ownerDocument.defaultView.innerHeight;returnrenderDocument(node.ownerDocument,options,width,height,index).then(function(canvas){**if(typeof(options.onrendered)==="function"){log("options.onrendered已弃用,html2canvas返回一个包含画布的Promise");options.onrendered(canvas);}returncanvas;});2.图像像素模糊:解决方法:添加dpi参数functionCanvasRenderer(width,height){Renderer.apply(this,arguments);这个.画布=这个。选项.画布||this.document.createElement("画布");如果(!this.options.canvas){如果(this.options.dpi){this.options.scale=this.options.d圆周率/96;//1CSS英寸=96px。}if(this.options.scale){this.canvas.style.width=width+'px';this.canvas.style.height=height+'px';this.canvas.width=Math.floor(width*this.options.scale);this.canvas.height=Math.floor(height*this.options.scale);this.ctx.scale(this.options.scale,this.options.scale);}else{this.canvas.width=width;this.canvas.height=高度;}}this.ctx=this.canvas.getContext("2d");this.taintCtx=this.document.createElement("canvas").getContext("2d");this.ctx.textBaseline="底部";this.variables={};log("InitializedCanvasRendererwithsize",width,"x",height)}returnparser.ready.then(function(){log("Finishedrendering");varcanvas;if(options.type==="view"){canvas=crop(renderer.canvas,{width:renderer.canvas.宽度,高度:renderer.canvas.height,top:0,left:0,x:0,y:0});}elseif(node===clonedWindow.document.body||node===clonedWindow.document.documentElement||options.canvas!=null){canvas=renderer.canvas;}elseif(options.scale){varorigBounds={width:options.width!=null?options.width:bounds.width,height:options.height!=null?options.height:bounds.height,top:bounds.top,left:bounds.left,x:0,y:0};varcropBounds={};for(varkeyinorigBounds){如果(origBounds.hasOwnProperty(key)){cropBounds[key]=origBounds[key]*options.scale;}}canvas=crop(renderer.canvas,cropBounds);canvas.style.width=origBounds.width+'px';canvas.style.height=origBounds.height+'px';}else{canvas=crop(renderer.canvas,{width:options.width!=null?options.width:bounds.width,height:options.height!=null?options.height:bounds.height,top:bounds.顶部,左侧:bounds.left,x:0,y:0});}cleanupContainer(容器,选项);返回画布;});参考链接:https://www.jianshu.com/p/f40...最后写下html2canvas的使用方法:varheight=$('.teacher_page').scrollTop()+$('.teacher_page').outerHeight(真的);html2canvas($(".teacher_page"),{height:height,//window.devicePixelRatio为设备像素比dpi:window.devicePixelRatio,}).then(function(canvas){varimgUri=canvas.toDataURL("image/png").replace("image/png","image/octet-stream");$('.popBody').html('');});官网:http://html2canvas.hertzen.com/下载地址:https://www.bootcdn.cn/html2C...