<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Canvas draw line example</title>
<meta charset="utf-8" />
</head>
<body style="position:relative;user-select:none">
<div style="font-size:25px;text-align:center;" id="canvasOffset">ss</div>
<button onclick="reset()" style="border:solid 1px #000;padding:10px;min-width:100px;font-weight:bold;margin-bottom:4px;">เริ่มเขียนใหม่</button>
<canvas id="canvas" style="border:solid 3px #000;display:block;"></canvas>
<script>
var divCanvasOffset = document.getElementById('canvasOffset');
let canvas = document.getElementById('canvas');
var rect = canvas.getBoundingClientRect();
let ctx = canvas.getContext('2d');
let isDraw = false;
let coord = { x: 0, y: 0 };
function reset() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
const drawCanvasOffset = () => {
//console.log(rect);
divCanvasOffset.innerText = `OffsetLeft: ${canvas.offsetLeft}, OffsetTop: ${canvas.offsetTop}, ClientRect: [left: ${rect.left}, top: ${rect.top}]`;
};
const doResize = () => {
canvas.width = 500; //window.innerWidth;
canvas.height = 700;// window.innerHeight;
};
const calPosition = (evt) => {
drawCanvasOffset();
//coord.x = evt.clientX - canvas.offsetLeft;
//coord.y = evt.clientY - canvas.offsetTop;
coord.x = evt.clientX - rect.left;
coord.y = evt.clientY - rect.top;
};
const drawLine = (evt) => {
if (!isDraw) return;
ctx.beginPath();
ctx.strokeStyle = '#ff0000';
ctx.lineWidth = 5;
ctx.lineCap = 'round'; // square, butt, round
ctx.moveTo(coord.x, coord.y);
calPosition(evt);
ctx.lineTo(coord.x, coord.y);
ctx.stroke();
ctx.closePath();
};
window.addEventListener('resize', doResize());
window.addEventListener('scroll', () => rect = canvas.getBoundingClientRect());
canvas.addEventListener('mousedown', e => {
isDraw = true;
calPosition(e);
});
canvas.addEventListener('mousemove', e => drawLine(e));
canvas.addEventListener('mouseup', () => isDraw = false);
</script>
</body>
</html>