convert div to image in javascript

To convert a div element to an image using Javascript, we can make use of the HTML5 canvas element. The basic steps are:

  1. Get the div element that needs to be converted to image.
  2. Create a canvas element dynamically and set its dimensions.
  3. Get the drawing context of the canvas and draw the div element on it.
  4. Convert the canvas to image using toDataURL() method.
  5. Create an img element and set its source to the image.
index.tsx
// get div element
const divElement = document.getElementById("myDiv");

// create canvas element
const canvas = document.createElement("canvas");
canvas.width = divElement.offsetWidth;
canvas.height = divElement.offsetHeight;

// get drawing context
const context = canvas.getContext("2d");

// draw div element on the canvas
context.drawInlineSVG(new XMLSerializer().serializeToString(divElement));

// convert canvas to image data url
const dataURL = canvas.toDataURL();

// create image element and set its source
const imgElement = document.createElement("img");
imgElement.src = dataURL;

// add image element to the DOM
document.body.appendChild(imgElement);
666 chars
24 lines

In the code above, replace "myDiv" with the id of the div element that you want to convert to image. This code will add the converted image at the end of the body element. You may modify it to add the image in a different position as per your requirements.

gistlibby LogSnag