JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Paint</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canv"></canvas>
<div class="colors">
<button class="color" style="background-color: red;"></button>
<button class="color" style="background-color: green;"></button>
<button class="color" style="background-color: blue;"></button>
<button class="color" style="background-color: yellow;"></button>
<button class="color" style="background-color: rgb(219, 14, 219);"></button>
<button class="color" style="background-color: black;"></button>
<button class="color" style="background-color: rgb(39, 198, 219);"></button>
<button class="color" style="background-color: rgb(255, 81, 0);"></button>
<button class="color" style="background-color: rgb(21, 255, 0);"></button>
<button class="color" style="background-color: rgb(132, 0, 255);"></button>
</div>
<script src="script.js"></script>
</body>
</html>
CSS
#canv {
width: 600px;
height: 300px;
border: 1px solid black;
position: relative;
top: 130px;
left: 50px;
background-color: rgb(247, 247, 247);
}
.colors {
position: absolute;
left: 750px;
top: 187px;
width: 120px;
display: flex;
flex-wrap: wrap;
}
.color {
width: 50px;
height: 50px;
margin-right: 7px;
margin-bottom: 5px;
}
JavaScript
const canvas = document.getElementById('canv'),
ctx = canvas.getContext('2d'),
colors = document.querySelectorAll('.color');
let color = "red";
let x = -3;
let y = -3;
let w = 3;
let h;
const cangeColor = () => {
for(let colour of colors) {
colour.onclick = () => {
color = colour.style.backgroundColor
}
}
}
let position = canvas.getBoundingClientRect();
console.log(position.width)
const brush = () => {
ctx.beginPath();
ctx.arc(x, y, w, 0, Math.PI * 2);
ctx.fillStyle = color;
ctx.fill();
ctx.closePath();
}
const mouseMove = e => {
if (e.clientX > position.x && e.clientX < position.x + position.width) {
//if(e.clientX > canvas.x && e.clientX < canvas.x + canvas.w) {
x = e.offsetX;
y = e.offsetY;
}
}
const brushDraw = () => {
brush();
requestAnimationFrame(brushDraw);
}
canvas.addEventListener('mousemove', mouseMove, false);
brushDraw();
cangeColor();