HTML Canvas Practice
Recently I learned how to use html canvas tag. After reading a bit of MDN, I built a simple position detect page. User can draw a line by clicking and when user click the start point, the line turns into red line and user no longer can draw line until user click the reset button.
Below is the JavaScript code for this small project and preview of the project.
const canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");
const resetButton = document.querySelector("button");
ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
let coordinates = [];
let line = new Path2D();
ctx.lineWidth = 5;
ctx.strokeStyle = "white";
const appendNewLine = (x, y) => {
if (coordinates.length <= 0) {
return line.moveTo(x, y);
}
const {x:prevX, y:prevY} = coordinates[coordinates.length - 1];
const newLine = new Path2D();
newLine.moveTo(prevX, prevY);
newLine.lineTo(x, y);
line.addPath(newLine);
ctx.stroke(line);
};
const addDot = (x, y) => {
const newDot = new Path2D();
newDot.arc(x, y, 5, 0, Math.PI * 2, true);
ctx.fillStyle = "white";
ctx.fill(newDot);
appendNewLine(x, y);
coordinates.push({
x,
y,
});
}
const isReturnToStart = (x, y) => {
if (coordinates.length > 0) {
const {x:startX, y:startY} = coordinates[0];
if (x <= startX + 5 && x >= startX - 5) {
if (y <= startY + 5 && y >= startY - 5) return true;
}
}
return false;
}
const drawLine = (e) => {
if (isReturnToStart(e.offsetX, e.offsetY)) {
appendNewLine(coordinates[0].x, coordinates[0].y);
ctx.strokeStyle = "red";
ctx.stroke(line);
console.log(coordinates);
return e.target.removeEventListener("click", drawLine);
}
addDot(e.offsetX, e.offsetY);
}
const resetCanvas = () => {
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
line = new Path2D();
ctx.lineWidth = 5;
ctx.strokeStyle = "white";
coordinates = [];
canvas.addEventListener("click", drawLine);
}
resetButton.addEventListener("click", resetCanvas);
canvas.addEventListener("click", drawLine);
You can see a Demo in here :D