Skip to content Skip to sidebar Skip to footer

Make A Div And It's Child Element's An Image In Javascript

I have this layout in HTML:
&

Solution 1:

Load the html2canvas js file, then add this:

$('#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>

You will need to change the image URL to something on the same domain (html2canvas does not load cross domain images).


Solution 2:

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;

    });

Post a Comment for "Make A Div And It's Child Element's An Image In Javascript"