웹 코드 영역을 이미지로 다운로드 하기

Eugenius1st·2024년 7월 23일
0

웹 코드 영역을 이미지로 다운로드 하기

은근 자주 구현하게 되는 코드이다.

라이브러리 없이 구현하는게 제일 마음 편해서 공유한다

Javascipt

document.getElementById('downloadBtn').addEventListener('click', function() {
    const captureElement = document.getElementById('capture');

    // Create a canvas element
    const canvas = document.createElement('canvas');
    canvas.width = captureElement.offsetWidth;
    canvas.height = captureElement.offsetHeight;
    const context = canvas.getContext('2d');

    // Draw the element on the canvas
    context.fillStyle = 'white'; // Set the background color if needed
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.drawImage(captureElement, 0, 0);

    // Convert canvas to data URL
    canvas.toDataURL('image/png', (dataUrl) => {
        // Create an anchor element and set the href attribute to the data URL
        const link = document.createElement('a');
        link.href = dataUrl;
        link.download = 'capture.png';
        link.click();
    });
});

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Div to Image</title>
</head>
<body>
    <div id="capture" style="width: 200px; height: 200px; background: lightblue; text-align: center; padding-top: 50px;">
        Capture this content
    </div>
    <button id="downloadBtn">Download as Image</button>

    <script src="script.js"></script>
</body>
</html>

html-to-image 라이브러리

리액트 컴포넌트 코드

import React, { useRef } from 'react';

const DivToImage = () => {
  const captureRef = useRef();

  const handleDownload = async () => {
    const captureElement = captureRef.current;

    // Create a canvas element
    const canvas = document.createElement('canvas');
    canvas.width = captureElement.offsetWidth;
    canvas.height = captureElement.offsetHeight;
    const context = canvas.getContext('2d');

    // Draw the element on the canvas
    context.fillStyle = 'white'; // Set the background color if needed
    context.fillRect(0, 0, canvas.width, canvas.height);

    // Draw the HTML element on the canvas
    const data = await htmlToImage.toPng(captureElement);
    const img = new Image();
    img.src = data;
    img.onload = () => {
      context.drawImage(img, 0, 0);
      // Convert canvas to data URL
      const dataUrl = canvas.toDataURL('image/png');

      // Create an anchor element and set the href attribute to the data URL
      const link = document.createElement('a');
      link.href = dataUrl;
      link.download = 'capture.png';
      link.click();
    };
  };

  return (
    <div>
      <div
        ref={captureRef}
        style={{
          width: '200px',
          height: '200px',
          background: 'lightblue',
          textAlign: 'center',
          paddingTop: '50px',
        }}
      >
        Capture this content
      </div>
      <button onClick={handleDownload} className="mt-2 p-2 bg-blue-500 text-white rounded">
        Download as Image
      </button>
    </div>
  );
};

export default DivToImage;

html2canvas 라이브러리

리액트 컴포넌트 코드

import React, { useRef } from 'react';

const DivToImage = () => {
  const captureRef = useRef();

  const handleDownload = () => {
    const captureElement = captureRef.current;

    // Create a canvas element
    const canvas = document.createElement('canvas');
    canvas.width = captureElement.offsetWidth;
    canvas.height = captureElement.offsetHeight;
    const context = canvas.getContext('2d');

    // Draw the element on the canvas
    context.fillStyle = 'white'; // Set the background color if needed
    context.fillRect(0, 0, canvas.width, canvas.height);

    // Use HTMLCanvasElement's drawImage method to draw the element
    html2canvas(captureElement).then(canvas => {
      const dataUrl = canvas.toDataURL('image/png');

      // Create an anchor element and set the href attribute to the data URL
      const link = document.createElement('a');
      link.href = dataUrl;
      link.download = 'capture.png';
      link.click();
    });
  };

  return (
    <div>
      <div
        ref={captureRef}
        style={{
          width: '200px',
          height: '200px',
          background: 'lightblue',
          textAlign: 'center',
          paddingTop: '50px',
        }}
      >
        Capture this content
      </div>
      <button onClick={handleDownload} className="mt-2 p-2 bg-blue-500 text-white rounded">
        Download as Image
      </button>
    </div>
  );
};

export default DivToImage;
profile
최강 프론트엔드 개발자가 되고싶은 안유진 입니다

0개의 댓글