<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<canvas id="canvas"></canvas>
<script src="./scripts.js"></script>
</body>
</html>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: flex;
background: linear-gradient(to right, #233c23, #0f9b0f);
}
#canvas {
width: 80%;
height: 90%;
margin: auto;
border-radius: 20px;
background: #fff;
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5);
}
const canvas = document.querySelector('#canvas');
const context = canvas.getContext('2d');
let isMouseUp = true,
hue = 0,
thickness = true,
x, y;
if (window.innerWidth) {
canvas.width = window.innerWidth * .9;
canvas.height = window.innerHeight * .9;
}
context.lineCap = 'round';
context.lineJoin = "round";
context.lineWidth = 100;
getClickPosition = (e) => {
isMouseUp = e.type == 'mouseup';
x = e.clientX;
y = e.clientY;
}
draw = (e) => {
if (isMouseUp) return;
context.strokeStyle = `hsl(${hue}, 100%, 50%)`;
context.beginPath();
context.moveTo(x, y);
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
[x, y] = [e.offsetX, e.offsetY];
hue++;
hue = hue % 360;
if (context.lineWidth > 100 || context.lineWidth <= 1) { thickness = !thickness; }
thickness ? context.lineWidth++ : context.lineWidth--;
}
canvas.addEventListener('mousedown', getClickPosition);
canvas.addEventListener('mouseup', getClickPosition);
canvas.addEventListener('mousemove', draw);