Comments (1)
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에 있는 자체 옵션으로 해결할 수 있었다.
- CORS 정책으로 인해 카드 영역에 있는 이미지가 캡처한 결과물에서는 보이지 않는 문제
- 캡처된 이미지는 직사각형이라 border-radius를 준 카드 영역만 이미지화 되지 않고 그 배경의 흰색 영역도 보여서 둥근 카드 느낌이 나지 않는 문제.
- 생성된 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의 컨텍스트를 얻어서 조작할 수 있다.
- 이미지를 새로 그릴 캔버스를 준비하고 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');
- 기존의 좌우반전된 canvas 이미지를 복사한다.
const img = new Image();
img.src = canvas.toDataURL('image/png');
- 복사한 이미지가 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)
- API document에 맞게 백엔드의 필드 구조와 로직을 수정한다.
- API 요청을 위한 환경설정을 한다.
- 카드 create API에 요청을 보내 카드를 생성하는 기능을 구현한다. HOT 2
- 앨범에 카드 정보를 불러와 렌더링하고 넘겨볼 수 있게 한다. HOT 1
- GET cards를 할 때 총 몇 개의 카드가 존재하는지 서버에서 값을 보내주도록 한다. HOT 1
- 앨범에서 카드를 클릭하면 카드 상세정보 페이지가 모달로 뜨게 라우팅 및 마크업을 한다.
- 앨범에서 카드를 누르면 상세정보를 조회할 수 있다.
- 카드 상세페이지에서 카드 뒤집기 기능을 추가한다. HOT 1
- 카드 상세정보 모달창에서 바깥 영역을 누르면 창이 닫히는 기능 추가 HOT 1
- 카드 수정 페이지를 만들고 저장된 카드 정보를 불러와 화면에 보여준다.
- Card Class를 만들어 submit 데이터를 만드는 과정을 추상화한다.
- 서버의 카드 update API에 발생하는 에러를 수정하고, update 페이지의 제출 버튼에 API 요청을 바인딩한다. HOT 1
- 카드 삭제를 확인하는 모달창을 마크업 하고, 모달창이 닫히는 기능을 구현한다.
- 카드 삭제 버튼을 누르면 카드 삭제 API에 요청하는 기능을 추가한다.
- 카드 삭제 후 메인으로 이동되었을 때 Book의 카드 목록에 삭제가 반영 안되는 문제 해결 HOT 1
- 카드 fetch 함수에서 페이지 가공하는 로직을 함수로 분리하고, 데이터를 알맞은 state 변수에 담도록 고친다.
- 카드 에디터 화면을 벗어나려고 하면 경고해주는 기능을 추가하자. HOT 1
- 페이지 전환 시 애니메이션 효과를 준다.
- 카드 에디터를 반응형 디자인으로 개선한다.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from phoca-review.