html2canvas将HTML内容写入Canvas生成图片

生而为人 谁不付出 谁不努力

html2canvas 能够实现在用户浏览器端直接对整个或部分页面进行截屏。这个html2canvas脚本将当页面渲染成一个Canvas图片,通过读取DOM并将不同的样式应用到这些元素上实现。·

它不需要来自服务器任何渲染,整张图片都是在客户端浏览器创建。当浏览器不支持Canvas时,将采用Flashcanvas或ExplorerCanvas技术代替实现。以下浏览器能够很好的支持该脚本:Firefox 3.5+, Google Chrome, Opera新的版本, IE9以上的浏览器。

参数名称类型默认值描述
allowTaintbooleanfalseWhether to allow cross-origin images to taint the canvas---允许跨域
backgroundstring#fffCanvas background color, if none is specified in DOM. Set undefined for transparent---canvas的背景颜色,如果没有设定默认透明
heightnumbernullDefine the heigt of the canvas in pixels. If null, renders with full height of the window.---canvas高度设定
letterRenderingbooleanfalseWhether to render each letter seperately. Necessary if letter-spacing is used.---在设置了字间距的时候有用
loggingbooleanfalseWhether to log events in the console.---在console.log()中输出信息
proxystringundefinedUrl to the proxy which is to be used for loading cross-origin images. If left empty, cross-origin images won't be loaded.---代理地址
taintTestbooleantrueWhether to test each image if it taints the canvas before drawing them---是否在渲染前测试图片
timeoutnumber0Timeout for loading images, in milliseconds. Setting it to 0 will result in no timeout.---图片加载延迟,默认延迟为0,单位毫秒
widthnumbernullDefine the width of the canvas in pixels. If null, renders with full width of the window.---canvas宽度
useCORSbooleanfalseWhether to attempt to load cross-origin images as CORS served, before reverting back to proxy--这个我也不知道是干嘛的

直接上实现代码

<!doctype html>
<html lang="en">
<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>指定区域生成图片</title>
  <script src="js/jquery-1.9.1.min.js"></script>
<script src="js/html2canvas.js"></script>
<script src="js/shareQrcode.js"></script>
<script src="js/canvas2image.js"></script>
<script src="layer/layer.js" type="text/javascript"></script>
</head>
<body class="bg-white">
<div class="modal-dialog dialog-result tqf" style="top:100%;" >
    <div class="content result-info">
	<!-- <img src="img/i-qq.png" /> -->
      <ul>
        <li class="title">测试结果</li>
        <li><b class="block jx_title">吉萨的粉红色的</b></li>
        <li class="title">测试说明</li>
        <li class="viewResult">是的发送到发送到否是的发送到发送到否是的发送到发送到否是的发送到发送到否</li>
      </ul>
    </div>
    <div class="code-bottom">
      <div class="fll" id="qrcode"></div>
      <h3 class="txt-overflow">几乎是大大</h3>
      <p><i class="icon icon-xs"></i>长按识别二维码快来测测吧</p>
      <p class="explain green">「心觉咨询」提供内容及技术支持</p>
    </div>
  </div>
  <footer class="no-border">
  <div class="btn-box tac">

    <a class="btn btn-radius btn-b-green btn-md" href="javascript:void(0)" onclick="show('.dialog')">
	<i class="icon icon-download"></i>保存结果后分享</a>
  </div>
</footer><h1>图片生成位置</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

<div class="modal-dialog dialog-result" id="share" style="display: none;">
 
        <li id="img" width="50%" ></li>
        <!--<img src="" width="100%" crossorigin="anonymous" id="img"/>-->
    
  </div>
</body>
</html>
/**
 * Created by Admin on 2018/11/12 0012.
 */

var times;
function show(obj) {
	layer.close(times);
	 times= layer.msg('海报生成中...', {
	  icon: 16,
	  shade: 0.2,
	  time: false
	});
    $(obj).toggle();
    saveShare();
}

function getBase64(imgUrl,imgId) {
	  window.URL = window.URL || window.webkitURL;
	  var xhr = new XMLHttpRequest();
	  xhr.open("get", imgUrl, true);
	  // 至关重要
	  xhr.responseType = "blob";
	  xhr.onload = function () {
	    if (this.status == 200) {
	      //得到一个blob对象
	      var blob = this.response;
	      console.log("blob", blob)
	      // 至关重要
	      let oFileReader = new FileReader();
	      oFileReader.onloadend = function (e) {
	        // 此处拿到的已经是 base64的图片了
	        let base64 = e.target.result;
	        console.log("方式一》》》》》》》》》", base64)
	        document.getElementById(imgId).src =  base64;
	      };
	      oFileReader.readAsDataURL(blob);
	      //====为了在页面显示图片,可以删除====
//	      var img = document.createElement("img");
//	      img.onload = function (e) {
//	        window.URL.revokeObjectURL(img.src); // 清除释放
//	      };
//	      let src = window.URL.createObjectURL(blob);
//	      img.src = src
	      //document.getElementById("container1").appendChild(img);
	      //====为了在页面显示图片,可以删除====

	    }
	  }
	  //xhr.send();
	}
function getImage (url,imgId) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'blob';
    xhr.send();
    xhr.onload = function () {
        if (this.status == 200) {
            document.getElementById(imgId).src =  URL.createObjectURL(this.response);
        }
    };
}


function getPixelRatio(context){
	var backingStore = context.backingStorePixelRatio ||
                    context.webkitBackingStorePixelRatio ||
                    context.mozBackingStorePixelRatio ||
                    context.msBackingStorePixelRatio ||
                    context.oBackingStorePixelRatio ||
                    context.backingStorePixelRatio || 1;
            return (window.devicePixelRatio || 1) / backingStore;
}
function saveShare(){	       
            var shareContent = document.querySelector('.tqf');// 需要绘制的部分的 (原生)dom 对象 ,注意容器的宽度不要使用百分比,使用固定宽度,避免缩放问题
            var width = shareContent.offsetWidth;  // 获取(原生)dom 宽度
            var height = shareContent.offsetHeight; // 获取(原生)dom 高
            var offsetTop = shareContent.offsetTop;  //元素距离顶部的偏移量

            var canvas = document.createElement('canvas');  //创建canvas 对象
            var context = canvas.getContext('2d');
            var scaleBy = getPixelRatio(context);  //获取像素密度的方法 (也可以采用自定义缩放比例)
            canvas.width = width * scaleBy;   //这里 由于绘制的dom 为固定宽度,居中,所以没有偏移
           canvas.height = (height + offsetTop) * scaleBy;  // 注意高度问题,由于顶部有个距离所以要加上顶部的距离,解决图像高度偏移问题
            context.scale(scaleBy, scaleBy);

            var opts = {
            	userCORS:true,
                allowTaint:true,//允许加载跨域的图片
                tainttest:true, //检测每张图片都已经加载完成
                scale:scaleBy, // 添加的scale 参数
                canvas:canvas, //自定义 canvas
                logging: true, //日志开关,发布的时候记得改成false
                width:width, //dom 原始宽度
                height:height //dom 原始高度
            };
            html2canvas(shareContent, opts).then(function (canvas) {
            	 let img = new Image();
            	 img.crossOrigin = "Anonymous";
                 let base64ImgSrc = canvas.toDataURL("image/png");
                 img.src = base64ImgSrc 
                 img.onload = function(){                
                     $('#share').css('display','block').css("margin-top","-225px");
                     $('#img').html(img)  //  w 674  h 938
                     $('#img img').css("width","100%");
                     layer.close(times);
                 }
				
            });
}



 

 

posted @ 2022-08-04 19:13  码奴生来只知道前进~  阅读(580)  评论(0编辑  收藏  举报