get visible part of background image of element as base64 in javascript

You can make use of canvas element to get the visible part of a background image of an element as a base64 string in JavaScript. Below is the code snippet that performs this task:

index.tsx
function getVisibleBackgroundImageAsBase64(element) {
  // Get computed styles of element
  const computedStyle = window.getComputedStyle(element);
  // Get background image and its position
  const backgroundImage = computedStyle.backgroundImage.slice(4, -1).replace(/"/g, "");
  const imagePosX = computedStyle.backgroundPositionX;
  const imagePosY = computedStyle.backgroundPositionY;
  // Create a new image element with the background image
  const image = new Image();
  image.src = backgroundImage;
  // Create a canvas element
  const canvas = document.createElement("canvas");
  canvas.width = parseInt(computedStyle.width);
  canvas.height = parseInt(computedStyle.height);
  // Draw the visible part of the background image on the canvas
  const ctx = canvas.getContext("2d");
  ctx.drawImage(image, parseInt(imagePosX), parseInt(imagePosY), canvas.width, canvas.height,
    0, 0, canvas.width, canvas.height);
  // Get base64 string of the visible part of the background image
  const base64 = canvas.toDataURL();
  return base64;
}
1046 chars
23 lines

You can call the above function by passing the element for which you want to get the visible part of the background image.

related categories

gistlibby LogSnag