LWC에서 Canvas 사용해서 글씨 쓰기 (1)

ahncheer·2024년 8월 9일
0

LWC & LWR

목록 보기
49/52
post-thumbnail

화면 미리보기

관련 CodePen
https://codesandbox.io/s/kaenbeoseugeurimpan-9t39h?from-embed=&file=/src/index.js:101-111

코드 작성

1-1. html 작성

<template>
    <div class="cpCanvas">
        <h4 class="page-title">Canvas Test</h4>
        <div class="canvas" style="width:100%"
            onmousemove={onMouseMove} onmousedown={startPainting}
            onmouseup={stopPainting} onmouseleave={stopPainting}></div>
    </div>
</template>

1-2. js 작성

import { LightningElement, track } from 'lwc';

export default class CpCanvas extends LightningElement {
    @track chartValue;
    @track painting = false;
    @track isFirstRender = true;
    async renderedCallback() {
        if (this.isFirstRender) {
            this.createCanvas();
            this.isFirstRender = false;
        }
    }
    createCanvas() {
        // Gauge 만들기 (CodePen) 참고
        const canvas = document.createElement('canvas');
        this.template.querySelector('div.canvas').appendChild(canvas);
        const ctx = canvas.getContext("2d");
        console.log('ctx : ', ctx);


        const width = 1000;
        const height = 500;

        canvas.width = width;
        canvas.height = height;
        canvas.style.margin = "10px";
        canvas.style.border = "3px double";
        ctx.strokeStyle = "#706671";
        ctx.lineWidth = 3;

        this.painting = false;

    }
    stopPainting(e) {
        console.log('stopPainting');
        this.painting = false;
    }

    startPainting(e) {
        console.log('startPainting');
        this.painting = true;
    } 

    
    onMouseMove(e) {
        console.log('onMouseMove');
        const ctx = this.template.querySelector('div.canvas canvas').getContext("2d");

        const x = e.offsetX;
        const y = e.offsetY;
            if (!this.painting) {
                ctx.beginPath();
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
                ctx.stroke();
            }
    }

}

1-3. css 작성

.cpCanvas{
    max-width: 1080px;
    margin: 0 auto;
}
.page-title{
    font-size: 24px;
    font-weight: bold;
    padding: 20px 0;
}

화면 확인

profile
개인 공부 기록용.

0개의 댓글