1
I’m building a simple program to draw on canvas where you can draw a circle and draw with the brush by clicking on certain buttons Desenhar círculo
(by clicking on canvas the circle is drawn) and Pincel
(moving the mouse over the canvas is done drawing with the brush):
let btnCircle = document.querySelector('#btn-circle');
let btnBrush = document.querySelector('#btn-brush');
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let mouseX, mouseY;
canvas.onmousemove = () => {
mouseX = event.offsetX;
mouseY = event.offsetY;
}
btnCircle.onclick = () => {
canvas.onclick = () => {
ctx.beginPath();
ctx.arc(mouseX, mouseY, 40, 0, 2 * Math.PI, false);
ctx.stroke();
};
}
btnBrush.onclick = () => {
canvas.onmousemove = () => {
mouseX = event.offsetX;
mouseY = event.offsetY;
ctx.fillStyle = 'red';
ctx.fillRect(mouseX - 10, mouseY - 10, 20, 20);
};
}
canvas {
display: block;
margin: 10px 0;
}
<button id="btn-circle">Desenhar círculo</button>
<button id="btn-brush">Pincel</button>
<canvas id="canvas" style="border: 1px solid #000;" width="500" height="500"></canvas>
So far it seems to be working well, but if, for example, I click the button Desenhar círculo
I can draw good circles and if I click the button Pincel
I can also draw with the brush, but clicking the two buttons ends up happening a problem I can draw at the same time with the brush and the circles which ends up generating a mess:
What was supposed to happen is when I hit the button Desenhar círculo
I draw just circles and when I click the button Pincel
I draw with just the brush, but it’s not happening because this is happening? and how can I solve this problem?
Thanks, @Guilherme Nascimento! truth I hadn’t thought of it
– felipe cardozo