html2canvas跨域问题

近期公司项目有个分享的功能,需要由前端生成包含有关用户信息的图片,点击可以保存。于是选用了html2canvas

github链接

https://github.com/niklasvh/html2canvas

官网链接

http://html2canvas.hertzen.com/

官网的案例

// document.body 可以替换成想要生成图片的dom元素
html2canvas(document.body, {
 onrendered: function(canvas) {
   document.body.appendChild(canvas);
 }
});

图片跨域

使用接口返回的图片数据,会出现以下报错(一般来说会出现下面的报错,但是在vue项目中没有报错)

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

解决:

方法一: 获取数据后,将图片先转为base64,再重新赋值到src 上。(缺点:需要每一张图片都进行一次转换)

方法二: 配置参数 useCORS: true

html2canvas(document.body, {
 useCORS: true,// 允许跨域
 onrendered: function(canvas) {
   document.body.appendChild(canvas);
 }
});

完美解决跨域和模糊的方法

网上的大神已经很好的解决了这个问题

https://segmentfault.com/q/1010000004006610
https://segmentfault.com/a/1190000007707209

我把解决代码贴一下

源码需要修改的地方有两处:

  1. 代码第 999 行 renderWindow 的方法中 修改判断条件 增加一个options.scale存在的条件

源码:

if (options.type === "view") {
              canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
          } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
              canvas = renderer.canvas;
          } else {
              canvas = crop(renderer.canvas, {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});

          }

改为:

if (options.type === "view") {
                canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
            } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement) {
                canvas = renderer.canvas;
            }else if(options.scale && options.canvas !=null){
                log("放大canvas",options.canvas);
                var scale = options.scale || 1;
                canvas = crop(renderer.canvas, {width: bounds.width * scale, height:bounds.height * scale, top: bounds.top *scale, left: bounds.left *scale, x: 0, y: 0});
            }
            else {
                canvas = crop(renderer.canvas, {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});
            }
  1. 代码第 943 行 html2canvas 的方法中 修改width,height

源码:

return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
    if (typeof(options.onrendered) === "function") {
        log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
        options.onrendered(canvas);
    }
    return canvas;
});

改为:

width = options.width != null ? options.width : node.ownerDocument.defaultView.innerWidth;
height = options.height != null ? options.height : node.ownerDocument.defaultView.innerHeight;
return renderDocument(node.ownerDocument, options, width, height, index).then(function(canvas) {
   if (typeof(options.onrendered) === "function") {
       log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
       options.onrendered(canvas);
   }
   return canvas;
});

使用方式:

html2Canvas() {
   const shareContent = document.getElementById('share-content') // 需要绘制的部分的 (原生)dom 对象 ,注意容器的宽度不要使用百分比,使用固定宽度,避免缩放问题
   const width = shareContent.offsetWidth // 获取(原生)dom 宽度
   const height = shareContent.offsetHeight // 获取(原生)dom 高
   const offsetTop = shareContent.offsetTop // 元素距离顶部的偏移量
   const canvas = document.createElement('canvas') // 创建canvas 对象
   const context = canvas.getContext('2d')
   const scaleBy = getPixelRatio(context) // 获取像素密度的方法 (也可以采用自定义缩放比例)
   canvas.width = width * scaleBy // 这里 由于绘制的dom 为固定宽度,居中,所以没有偏移
   canvas.height = (height + offsetTop) * scaleBy // 注意高度问题,由于顶部有个距离所以要加上顶部的距离,解决图像高度偏移问题
   context.scale(scaleBy, scaleBy)
   const opts = {
     // allowTaint: true, // 允许加载跨域的图片 (使用这个会报错)
     useCORS: true,  // 允许加载跨域图片
     tainttest: true, // 检测每张图片都已经加载完成
     scale: scaleBy, // 添加的scale 参数
     canvas: canvas, // 自定义 canvas
     // logging: true, // 日志开关,发布的时候记得改成false
     width: width, // dom 原始宽度
     height: height // dom 原始高度
   }
   html2canvas(shareContent, opts).then(function (canvas) {
     const _src = canvas.toDataURL()
     const img = document.createElement('img')
     img.id = 'shareImgCanvas'
     img.src = _src
     img.style.cssText = 'width: 100%;'
     console.log('html2canvas')
   })
 },
 getPixelRatio(context) { // 获取设备的pixel ratio
   const backingStore = context.backingStorePixelRatio ||
   context.webkitBackingStorePixelRatio ||
   context.mozBackingStorePixelRatio ||
   context.msBackingStorePixelRatio ||
   context.oBackingStorePixelRatio ||
   context.backingStorePixelRatio || 1
   return (window.devicePixelRatio || 1) / backingStore
 }

需要注意的几个方面:

  1. 由于图片数据都是动态加载的,css样式不起作用,可以在生成图片的时候要加上样式
img.style.cssText = 'width: 100%;'
  1. 需要生成图片的dom背景不能透明,也不能设置为display:none,否则截图出来就会是透明的图片或者一片空白。如果不想将生成图片的dom展示给用户,可以将dom层级降低.
// 如果内容过多,视图可以滚动,则要设置为fixed,使得dom一直处于视图内,不然无法正确的截取到dom
// left 、top最好设置为0,否则在生成图片的时候会把偏移量计算出来,生成的图片会有偏移量相对应的空白高度
position: fixed; 
left:0;
top:0;
z-index: -1;
  1. 不要使用背景图片

源码里也有说明

image.png
  1. 版本选择

html2canvas 0.5.n的beta版本中已经采用了iframe rendering的方法,作者也有说明

image.png

将ops中的logging: true打开会看到整个过程

image.png

在源码中注释1023行的removeChild,可以看的更加清晰

image.png

再次操作,会发现页面中多了一个iframe,它是将这个dom树都clone了一遍,再插入body中

image.png

如果是移动端,同时有多个数据以列表的方式展示,那每次点击生成图片都会把页面中的图片重新加载一次,这样多次请求会让页面加载特别慢。

解决:
1、跳到新的页面,避免需要生成图片的dom装载太多数据。
2、使用低版本的html2canvas

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,042评论 25 707
  • 1. 什么是跨域? 跨域一词从字面意思看,就是跨域名嘛,但实际上跨域的范围绝对不止那么狭隘。具体概念如下:只要协议...
    他在发呆阅读 820评论 0 0
  • 最近看到一则新闻,一家创业公司提供死亡体验服务,让体验者躺在野外挖好的坟墓里,近距离的体验死亡的感觉。网友在跟帖中...
    门前池塘阅读 394评论 0 0
  • 朋友一起逛街,她带着四岁的儿子。小孩子精力旺盛,总是喜欢跑跑跳跳,过马路的时候也不让人省心。朋友一遍又一遍扯着嗓子...
    Doctor方阅读 436评论 1 5
  • 我们都要变成大人了。 我叫__。 大家都说,青春是一本谱不完的书,总在少年不知不觉中,悄悄消逝、离去。如何面对一个...
    11xi阅读 532评论 8 5