html2canvas插件生成图片

 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

开发工具与关键技术:VS、jQuery

作者:#33

撰写时间:撰写时间:2019年06月17日

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

MVC学习,练习html2canvas插件生成图片的方法:

首先需要引入html2canvas插件:<script src="~/Plugins/html2canvas.js"></script>

上图右边的div块,工作证盒子布局的源代码:

<div class="row mt-1">

    <div class="col-lg-7 px-1">

        <table id="tabemployee" lay-filter="tab"> </table>

    </div>

    <div class="col-lg-5 pt-1 px-1 mt-2">

        <div id="employeebox" class="employeebox mb-4">

            <div class="employeeInfor w-100">

      <img src="~/Content/002.PNG" class="employeeimg" id="employeeimg" />

      <div class="employee_p">

<p class="employee_card  text-center">员工工作证</p><p class="YGInfor">姓名:<label id="EmployeeName"></label></p><p class="YGInfor">部门:<label id="Department"></label></p><p class="YGInfor">职务:<label id="Job"></label></p>

 </div> </div></div><div class="text-center">

 <button class="btn btn-outline-primary" onclick="Employee_Image()">生成图片</button>

 <button class="btn btn-outline-secondary" onclick="PrintImage()">打印图片</button>

 </div></div></div>

生成图片的窗口Modal

<div class="modal fade" id="employeeImage">

  <div class="modal-employee" role="document">

<div class="modal-content">

<div class="modal-header">

 <h5 class="modal-title text-center">工作证下载</h5>

       <button type="button" class="close" data-dismiss="modal" aria-label="Close">

           <span aria-hidden="true">&times;</span>

       </button> </div>

     <div class="modal-body text-center">

<imgsrc="#"alt="Alternate Text"id="modEmployeeImg"style="width:350px;height:450px;"/> </div>

      <div class="modal-footer justify-content-center">

         <p class="text-center"> 温馨提示:右键可下载图片</p>

</div></div> </div> </div>

点击生成图片按钮弹出模态窗体,生成图片:获取盒子id通过width()方法得到宽度并赋值给图片,等于图片的宽度,通过插件的方法获取元素盒子生成图片,canvas.toDataURL()生成图片数据。打印图片:添加img元素,并赋值图片链接,通过window.open()打开新的界面打印图片。

生成图片和打印图片的方法:

function Employee_Image() {//生成图片

   var width = $(".employeebox").width();

   $("#employeeimg .modal-employee").width(width);

   var employeeName = $("#employeeName").text().trim();

      html2canvas($("#employeebox"), {

       onrendered: function (canvas) {

        var dataUrl = canvas.toDataURL();

        $("#modEmployeeImg").attr("src", dataUrl); } });

          $("#employeeImage").modal();}//打开模态窗体

function PrintImage() {//打印图片

  var employeeName = $("#employeeName").text().trim();

      html2canvas($("#employeebox"), {

        onrendered: function (canvas) {

          var dataUrl = canvas.toDataURL();

          var newImage = document.createElement('img');

            newImage.src = dataUrl; //图片链接

            var printWindow = window.open();

            printWindow.document.body.appendChild(newImage);} });}

猜你喜欢

转载自blog.csdn.net/weixin_44484621/article/details/92760480