관련 CodePen
https://codesandbox.io/s/kaenbeoseugeurimpan-9t39h?from-embed=&file=/src/index.js:101-111
<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>
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();
}
}
}
.cpCanvas{
max-width: 1080px;
margin: 0 auto;
}
.page-title{
font-size: 24px;
font-weight: bold;
padding: 20px 0;
}