perfect pixel to canvas

pixgram·2022년 1월 13일
0

css에서 1px은 가상 96dpi디스플레이에서의 1px크기이다. 가상 디스플레이가 기준이므로 'CSS픽셀'이라는 이름으로 불린다. css작업을 하면서 적은 수치(ex top: 10px)는 위치와 측정용으로 사용이 되고 실제 브라우져에서 렌더링 될때 모니터에 맞게 브라우져 내부에서 물리적인 픽셀로 변경된다. 이때문에 브라우져 엔진마다 오차가 생기게 된다. 소수점을 반올림 하느냐 반내림 하느냐 등등의 계산 방식이 다르다.

canvas에서 그려지는 요소들은 각 디스플레이 밀도(레티나는 css픽셀 1개를 물리적인 픽셀 2개를 사용해서 표현한다)에 맞게 표현되야 하는데, css는 96dpi기준이므로 canvas요소를 css를 사용하여 크기를 조정하는건 맞지 않다.

아래는 픽셀-퍼펙트에 가까운 캔버스를 만들기 위한 방법중 하나이다.

this.stageWidth = document.body.clientWidth;
this.stageHeight = document.body.clientHeight;

this.pixelRatio = window.devicePixelRatio > 1 ? 2: 1;

this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d');

this.canvas.width = this.stageWidth * this.pixelRatio;
this.canvas.height = this.stageHeight * this.pixelRatio;
this.ctx.scale(this.pixelRatio, this.pixelRatio);

참고: https://ui.toast.com/weekly-pick/ko_20200728

profile
Interactive Front-end Developer and WebGL Artist

0개의 댓글