Simple Canvas Drawing
by Dominic Myers
HTML
<canvas id="canvas" width="500" height="300"></canvas>
CSS
#canvas {
border: 1px solid black
}
JavaScript
const rectangles = [];
(() => {
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
let x, y, width, height;
const redraw = (callback) => {
context.clearRect(0, 0, canvas.width, canvas.height);
if (rectangles.length) {
rectangles.forEach((rectangle) => {
context.fillRect(
rectangle.x,
rectangle.y,
rectangle.width,
rectangle.height
);
})
}
if (callback) {
callback();
}
};
canvas.addEventListener("mousedown", (event) => {
if (typeof(x) === "undefined" || x === null) {
x = event.pageX - canvas.offsetLeft;
y = event.pageY - canvas.offsetTop;
}
});
canvas.addEventListener("mousemove", (event) => {
if (typeof(x) !== "undefined" && x !== null) {
width = (event.pageX - canvas.offsetLeft) - x;
height = (event.pageY - canvas.offsetTop) - y;
redraw(() => {
context.fillRect(x, y, width, height);
});
}
});
canvas.addEventListener("mouseup", (event) => {
if (typeof(x) !== "undefined" && x !== null) {
width = (event.pageX - canvas.offsetLeft) - x;
height = (event.pageY - canvas.offsetTop) - y;
rectangles.push({
x: x,
y: y,
width: width,
height: height
});
x = null;
y = null;
width = null;
height = null;
}
});
})();