sroxck

sroxck

Webpage content displayed as an image

The requirement is to convert the Vue detail page into an image display to avoid machine crawling of text data and increase the difficulty of crawler parsing.

Idea#

Convert HTML to canvas, then convert the canvas to an image.

Solution#

Use the html2canvas library to achieve this.

import html2canvas from "html2canvas";

/**
 * Convert HTML to base64 and return
 * @param {*} target
 * @param {*} width
 * @param {*} height
 * @returns
 */
export async function htmlToBase64(target, width, height) {
  const element = document.querySelector(target);
  const copyElement = element.cloneNode(true);
  element.style.width = width;
  const canvas = await html2canvas(element);
  element.style.width = copyElement.style.width;
  const base64Data = canvas.toDataURL("image/png");
  return base64Data;
}

/**
 * Convert HTML to Canvas and return
 * @param {*} target
 * @param {*} width
 * @param {*} height
 * @returns
 */
export async function htmlToCanvas(target, width, height) {
  const element = document.querySelector(target);
  const copyElement = element.cloneNode(true);
  element.style.width = width;
  const canvas = await html2canvas(element);
  element.style.width = copyElement.style.width;
  return canvas; // Return canvas object
}

We convert it to base64 and then set the base64 as the src attribute of the img.

This article is synchronized and updated to xLog by Mix Space Original link: http://www.sroxck.top/posts/fontend/html2canvas

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.