html to image in javascript

Using JavaScript and the canvas element, you can generate an image from HTML. Here is a sample code:

index.tsx
// Get the HTML element you want to capture
const element = document.getElementById('my-html-element');

// Create a canvas element
const canvas = document.createElement('canvas');
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;

// Get the canvas 2D context and draw the element on it
const context = canvas.getContext('2d');
context.drawImage(element, 0, 0, element.offsetWidth, element.offsetHeight);

// Convert the canvas to a data URL and set it as the source of an image element
const img = new Image();
img.src = canvas.toDataURL('image/png');

// Append the image element to the document
document.appendChild(img);
650 chars
19 lines

In this code, replace my-html-element with the ID of the HTML element you want to capture. The resulting image will be a PNG encoded as a base64 data URL, which you can then use in your application.

gistlibby LogSnag