Giter Club home page Giter Club logo

Comments (1)

bluepebble25 avatar bluepebble25 commented on June 12, 2024

html2canvas 사용방법

  • 설치

npm install html2canvas

  • 사용 예시 (화면 영역 캡처한 뒤 생성된 이미지를 a 태그 이용해 자동으로 다운로드해주는 예시)
import html2canvas from 'html2canvas';

const onClickDownload = () => {
  html2canvas(cardRef.current, {
    useCORS: true,
    allowTaint: true,
    backgroundColor: 'rgba(0,0,0,0)',
  }).then((canvas) => {
    const url = canvas.toDataURL('image/png');
    downloadFile(url, 'flower');
  });
};

function downloadFile(fileUrl: string, fileName: string) {
  const a = document.createElement('a');
  a.href = fileUrl;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

겪은 문제 - html2canvas 관련

html2canvas 설정으로 인해 생긴 문제가 세 가지 있었다.
다음과 같은 문제는 html2canvas에 있는 자체 옵션으로 해결할 수 있었다.

  1. CORS 정책으로 인해 카드 영역에 있는 이미지가 캡처한 결과물에서는 보이지 않는 문제
  2. 캡처된 이미지는 직사각형이라 border-radius를 준 카드 영역만 이미지화 되지 않고 그 배경의 흰색 영역도 보여서 둥근 카드 느낌이 나지 않는 문제.
  3. 생성된 canvas를 이미지로 다운받으려고 canvas.toDataURL('image/png')로 url을 구하려 했는데 CORS 관련으로 인해 변환할 수 없었음.

해결

  • allowTaint : CORS 이미지 캡처를 허용할 것인지 true/false
  • useCORS : CORS 이미지를 toDataURL() 할 수 있게 허용 true/false
  • backgroundColor : 뒷 배경의 색깔 지정. backgroundColor: rgba(0,0,0,0)으로 배경을 투명하게 설정해서, 둥근 모서리를 갖는 카드만 보이는 png 파일을 만들 수 있었다.

겪은 문제 - 카드의 뒤집힌 뒷면을 캡처해서 이미지가 좌우반전되어 생성되는 문제

카드를 flip 하지 않은 채로 뒷면도 한꺼번에 캡처하려다 보니 캡처한 이미지가 좌우 반전으로 생성된다.

해결

생성된 이미지를 또 다른 캔버스에 좌우반전해서 새로 그린다음 저장한다.

  • canvas.getContext('2d')로 canvas의 컨텍스트를 얻어서 조작할 수 있다.
  1. 이미지를 새로 그릴 캔버스를 준비하고 context를 얻어놓는다.
const flippedCanvas = document.createElement('canvas');
flippedCanvas.width = canvas.width;
flippedCanvas.height = canvas.height;
flippedCanvas.style.display = 'none';
document.body.appendChild(flippedCanvas);
const ctx = flippedCanvas.getContext('2d');
  1. 기존의 좌우반전된 canvas 이미지를 복사한다.
const img = new Image();
img.src = canvas.toDataURL('image/png');
  1. 복사한 이미지가 onload되면 context를 이용해 이미지를 좌우반전해서 그린다.
img.onload = () => {
  ctx.scale(-1, 1);
  ctx.drawImage(img, img.width * -1, 0);
  const imgURL = flippedCanvas.toDataURL('image/png');
  downloadFile(imgURL, 'myCard');
  document.body.removeChild(flippedCanvas);
};

from phoca-review.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.