How to Create an Image from a Div Using jQuery?

Estimated read time 3 min read

To create an image from a div using jQuery, you can follow these steps:

  1. Create an HTML file with a div containing the content you want to convert to an image.
  2. Add CSS to style the div and its content.
  3. Write the jQuery code to create an image from the div using the html2canvas library.

Here’s an example code that demonstrates how to create an image from a div using jQuery:


<!DOCTYPE html>
  <title>Create an Image from a Div</title>
  <script src=""></script>
  <script src=""></script>
    #content {
      margin: 20px;
      padding: 20px;
      background-color: #fff;
      border: 1px solid #ccc;
      border-radius: 5px;
      box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
      font-size: 16px;
      line-height: 1.5;
  <div id="content">
    <h1>Create an Image from a Div</h1>
    <p>This is an example of how to create an image from a div using jQuery and the html2canvas library.</p>
    <img src="your-image-source.jpg" alt="your-image-description">
  <button id="create-image">Create Image</button>


$(document).ready(function() {
  $('#create-image').click(function() {
    html2canvas($('#content'), {
      onrendered: function(canvas) {
        var img = canvas.toDataURL();;


The JavaScript code sets a click event listener on the create-image button. When the button is clicked, the html2canvas library is used to create an image from the content div.

The html2canvas() function takes two arguments: the div element to convert to an image and an options object. The options object includes an onrendered property that specifies a callback function to execute when the rendering is complete.

The onrendered callback function takes a canvas object as its argument. The toDataURL() method of the canvas object creates a base64-encoded string of the image data. The method opens the base64-encoded image data in a new window.

You can customize the CSS and JavaScript code to create different types of images from divs. For example, you can add a download button to save the image to the user’s computer or modify the html2canvas options object to include image dimensions and quality.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply