본문 바로가기
개발(Development)/HTML, CSS

HTML Canvas 왜곡현상(선 두께 불일치, 비대칭, 비율 불균형 등) 해결 방법

by 카레유 2021. 3. 28.

HTML에서는 아래와 같이 canvas태그를 이용하면, 쉽게 그림을 그릴 수 있다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* canvas 태그 크기 설정 */
        #myCanvas{
            width: 500px; height: 400px;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <!-- canvas 태그 생성 -->
    <canvas id="myCanvas" ></canvas>

    <script>
        // 1. canvas 엘리먼트 취득
        const canvas = document.getElementById('myCanvas');

        // 2. 2d그래픽 설정 및 그리기 객체 취득
        const ctx = canvas.getContext("2d");

        // 3. 그리기 시작
        ctx.beginPath();

        // 4. 시작점 설정
        ctx.moveTo(100, 50);

        // 5. 첫번째 이동지점 설정
        ctx.lineTo(200, 50);

        // 6. 두번째 이동지점 설정
        ctx.lineTo(200, 100);

        // 7. 선 두께&색상 설정
        ctx.lineWidth = 10; // 선 두께 설정
        ctx.strokeStyle = 'blue'; // 선 색 설정

        // 8. 선 그리기
        ctx.stroke();
    </script>
</body>
</html>

 

오른쪽으로 갔다가 아래로 내려가는 선을 그리는 코드다.

(나름대로 상세하게 주석을 달았다)

 

그런데 웹페이지에 띄워보면... 가로 세로 선 두께가 다른 것을 알 수 있다.

아주 기초적인 내용이지만, 모르고 있으면 난감한 내용이다.

 

이 현상은 그래픽적인 요소를 CSS로 별도 처리하는 좋은(?) 습관으로 인해 발생하는 문제다.

(내가 그랬다.... ㅋㅋㅋ)

 

MDN사이트 canvas 튜토리얼을 보면 이런 문장이 있다.

 

Note: If your renderings seem distorted, try specifying your width and height attributes explicitly in the <canvas> attributes, and not using CSS.

출처: developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage

 

 

웹브라우저에 띄웠을 때 그림이 왜곡되어 보인다면,

"canvas 사이즈를 CSS로 조정하지 말고, canvas 태그자체에 직접 width, height를 설정하라"는 말이다.

 

즉, 이런식으로 작성하라는 것 같다.

<canvas id="myCanvas" width="500" height="400"></canvas>

 

전체 코드는 아래와 같다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* canvas 태그 크기 설정 */
        #myCanvas{
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <!-- canvas 태그 생성 -->
    <canvas id="myCanvas" width="500" height="400"></canvas>

    <script>
        // 1. canvas 엘리먼트 취득
        const canvas = document.getElementById('myCanvas');

        // 2. 2d그래픽 설정 및 그리기 객체 취득
        const ctx = canvas.getContext("2d");

        // 3. 그리기 시작
        ctx.beginPath();

        // 4. 시작점 설정
        ctx.moveTo(100, 50);

        // 5. 첫번째 이동지점 설정
        ctx.lineTo(200, 50);

        // 6. 두번째 이동지점 설정
        ctx.lineTo(200, 100);

        // 7. 선 두께&색상 설정
        ctx.lineWidth = 10; // 선 두께 설정
        ctx.strokeStyle = 'blue'; // 선 색 설정

        // 8. 선 그리기
        ctx.stroke();
    </script>
</body>
</html>

 

결과는 완벽하다.

 

 

댓글