制作一个Div,它的子元素是Javascript中的一个图像

时间:2015-03-02 05:34:24

标签: javascript jquery html css

我在HTML中有这个布局:

<div id="front">
    <img id="student_front" src="' . $path . '/images/student_front.jpg"></img>
    <img id="myid_info_photo"></img>
    <div id="myid_info_college">CEIT</div>
    <div id="myid_info_idnumber">101-03043</div>
    <img id="myid_info_signature"></img>
    <div id="myid_info_course">BSCS</div>
    <div id="myid_info_name">Alyssa E. Gono</div>
    <div id="myid_info_barcode"></div>
</div>

我想生成一个jpeg文件,其中div #front将出现在我的屏幕中。我将如何在Javascript中执行此操作?我有一个按钮,当它点击时会调用一个动作。

function myid_print_id() {
    win = window.open(document.getElementById("student_front").src,"_blank");
    win.onload = function() { 
        win.print(); 
    }
}

$('#myid_print_id').on('click', function(e) {
    e.preventDefault();  
    myid_print_id();

});

myid_print_id()函数只检索图像文件。我想用id&#34; front&#34;来检索我整个div的外观。

2 个答案:

答案 0 :(得分:1)

加载html2canvas js文件,然后添加:

$('#btn').click(function() {
  html2canvas($('#front'), {
    onrendered: function(canvas) {
      myImage = canvas.toDataURL("image/png");
      $('#output').append(canvas);
    }
  });
});
#output {
  border: 1px solid #888888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<div id="front">
  <img id="student_front" src="http://lorempixel.com/400/200">
  <div id="myid_info_college">CEIT</div>
  <div id="myid_info_idnumber">101-03043</div>
  <div id="myid_info_course">BSCS</div>
  <div id="myid_info_name">Alyssa E. Gono</div>
  <div id="myid_info_barcode">More text</div>
</div>
<button id="btn">CLICK FOR PIC</button>
<br>
<div id="output"></div>

您需要将图片网址更改为同一网域上的内容(html2canvas不会加载跨域图片)。

答案 1 :(得分:0)

HTML

<div>
    <input type="button" id="btnGenerateImage" value="Generate Image" />
</div>


<div>
    <canvas id="myCanvas"></canvas>
</div>
<div>
    <h1>
        Generated Content</h1>
    <img id="canvasImg" alt="Right click to save me!">
</div>

SCRIPT

 $("#btnGenerateImage").on('click', function () {
        var canvas = document.getElementById('myCanvas');

        // save canvas image as data url (png format by default)
        var dataURL = canvas.toDataURL();

        // set canvasImg image src to dataURL
        // so it can be saved as an image
        document.getElementById('canvasImg').src = dataURL;

    });