applan의 개발 이야기

[오류해결] HTML canvas 안 나오는 문제 ( width 사용 ) 본문

개발/Dev.

[오류해결] HTML canvas 안 나오는 문제 ( width 사용 )

applan 2022. 8. 22. 15:18
728x90

💥 발생

다음 HTML 소스에서 버튼을 클릭하면 canvas 에 테스트, 123123 이 나와야하는데 123123이 나오지 않는 현상 발생

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  <script>
    $(() => {
        let canvas = document.getElementById('testCanvas');
        let ctx = canvas.getContext('2d');
        let canvasWidth = $('#testCanvas').width();
        ctx.font = "15px 맑은 고딕";

        ctx.textAlign = "start";
        ctx.fillText("테스트", 0, 15);
        ctx.textAlign = "end";
        ctx.fillText("123123", canvasWidth, 15);
        ctx.stroke();
    })

    const handle_canvas_show_btn = () => {
        $("#test").show();
    }
  </script>
</head>
<body>
    <button onclick="handle_canvas_show_btn()">캔버스 표기</button>
    <div id="test" style="display: none">
      <canvas id="testCanvas" width="800"></canvas>
    </div>
</body>
</html>

123123... 너 어디갔니???

🧑‍💻 문제 확인

Chrome 의 inspect 로 화면을 띄워서 디버깅 진행

뭐가 문제지... 해매다가 한가지 이상한 점을 확인 

..? canvasWidth 값이 왜 0이지..? 분명 800으로 줬는데...?

🤔 문제 해결 과정

이상함을 감지하고 바로 소스에 다음 console.log 추가

$(() => {
    let canvas = document.getElementById('testCanvas');
    let ctx = canvas.getContext('2d');
    let canvasWidth = $('#testCanvas').width();
    ctx.font = "15px 맑은 고딕";

    ctx.textAlign = "start";
    ctx.fillText("테스트", 0, 15);
    ctx.textAlign = "end";
    ctx.fillText("123123", canvasWidth, 15);
    ctx.stroke();
    console.log(canvasWidth); // <--- 추가
})

const handle_canvas_show_btn = () => {
    $("#test").show();
}


// 출력 결과
0

😃 문제 해결

값이 0이 나오는 것을 보고 이상함을 감지하고

부모의 태그가 display:none 인 경우 발생하는 문제로 보여지는 것 같아서 다음과 같이 소스 수정

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
  <script>
    /** $(() => {
        let canvas = document.getElementById('testCanvas');
        let ctx = canvas.getContext('2d');
        let canvasWidth = $('#testCanvas').width();
        ctx.font = "15px 맑은 고딕";

        ctx.textAlign = "start";
        ctx.fillText("테스트", 0, 15);
        ctx.textAlign = "end";
        ctx.fillText("123123", canvasWidth, 15);
        ctx.stroke();
        console.log(canvasWidth);
    }) */

    const handle_canvas_show_btn = () => {
        $("#test").show();
        let canvas = document.getElementById('testCanvas');
        let ctx = canvas.getContext('2d');
        let canvasWidth = $('#testCanvas').width();
        ctx.font = "15px 맑은 고딕";

        ctx.textAlign = "start";
        ctx.fillText("테스트", 0, 15);
        ctx.textAlign = "end";
        ctx.fillText("123123", canvasWidth, 15);
        ctx.stroke();
    }
  </script>
</head>
<body>
    <button onclick="handle_canvas_show_btn()">캔버스 표기</button>
    <div id="test" style="display: none">
      <canvas id="testCanvas" width="800"></canvas>
    </div>
</body>
</html>

이대로 실행해보니 잘 나오는 것을 확인!!

🎓 배운점 

- canvas 속성 중 width 값은 부모 태그가 display:none 인 경우 자동으로 0으로 잡힌다. 

 

🧩 추가로 궁금

그럼 만약... 부모 태그가 보여진 뒤에 width 값을 찍으면 어떻게 나올까?

const handle_canvas_show_btn = () => {
    $("#test").show();
    let canvasWidth = $('#testCanvas').width();
    console.log("등장 후 width");
    console.log(canvasWidth);
}

결과는...?

대박.. 보여진 뒤에는 제대로 width 값이 인식한다!!!

 

728x90
Comments