Capture HTML Elements And Download As An Image - jQuery Screenshot

Capture HTML Elements And Download As An Image - jQuery Screenshot

A jQuery script which makes uses of html2canvas.js and canvas2image.js to capture the screenshot of specific HTML elements.

You can specify the height, width, file name and file type (png, jpg, or bmp) before downloading the screenshot.

Dependencies:

How to use it:

1. Load the required resources in your html document.

<script src="https://code.jquery.com/jquery-3.3.1.min.js" 
        integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" 
        crossorigin="anonymous">
</script>
<script src="html2canvas.min.js"></script>
<script src="canvas2image.js"></script>

2. Create a trigger element that will take the screenshot of a specific HTML node.

<h2 class="toCanvas"> 
  To Canvas 
</h2>

3. Create a trigger element that will convert the canvas into a downloadable image.

<h2 class="toPic"> 
  To Image
</h2>

4. Create form controls to customize the image output.

<label for="imgW">Image Width:</label>
<input type="number" value="" id="imgW" placeholder="Image Width" />
<label for="imgH">Image Height:</label>
<input type="number" value="" id="imgH" placeholder="Image Height" />
<label for="imgFileName">File Name:</label>
<input type="text" placeholder="File Name" id="imgFileName" />
<select id="sel">
  <option value="png">png</option>
  <option value="jpeg">jpeg</option>
  <option value="bmp">bmp</option>
</select>
<button id="save">Save And Download</button>

5. Specify the HTML node you want to take the screenshot.

<div class="example">
  ...
</div>
var test = $(".example").get(0);

6. The main JavaScript to take a screenshot of the HTML node.

// to canvas
$('.toCanvas').click(function(e) {
  html2canvas(test).then(function(canvas) {
    // canvas width
    var canvasWidth = canvas.width;
    // canvas height
    var canvasHeight = canvas.height;
    // render canvas
    $('.toCanvas').after(canvas);
    // show 'to image' button
    $('.toPic').show(1000);
    // convert canvas to image
    $('.toPic').click(function(e) {
      var img = Canvas2Image.convertToImage(canvas, canvasWidth, canvasHeight);
      // render image
      $(".toPic").after(img);
      // save
      $('#save').click(function(e) {
        let type = $('#sel').val(); // image type
        let w = $('#imgW').val(); // image width
        let h = $('#imgH').val(); // image height
        let f = $('#imgFileName').val(); // file name
        w = (w === '') ? canvasWidth : w; 
        h = (h === '') ? canvasHeight : h;
        // save as image
        Canvas2Image.saveAsImage(canvas, w, h, type, f);
      });
    });
  });
});

This awesome jQuery plugin is developed by usecodelee. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 31.08.2018
  • Source