console
document.body.onload = function () {
new Carxame(document.getElementById('demo'));
}
class Carxame {
constructor(container) {
this.canvas = document.createElement('canvas');
container.replaceWith(this.canvas);
this.canvas.style.backgroundColor = '#ccc';
this.resize();
this.ctx = this.canvas.getContext('2d');
this.isDrawing = false;
this.points = [];
this.lastPoint = null;
this.sampleDistance = 5;
window.addEventListener('resize', () => this.resize());
this.canvas.addEventListener('mousedown', this.startDrawing.bind(this));
this.canvas.addEventListener('mousemove', this.draw.bind(this));
this.canvas.addEventListener('mouseup', this.stopDrawing.bind(this));
this.canvas.addEventListener('mouseleave', this.stopDrawing.bind(this));
}
startDrawing(event) {
this.isDrawing = true;
this.points.push({ x: event.clientX, y: event.clientY });
this.lastPoint = { x: event.clientX, y: event.clientY };
}
draw(event) {
if (!this.isDrawing) return;
const distance = Math.sqrt(
Math.pow(event.clientX - this.lastPoint.x, 2) +
Math.pow(event.clientY - this.lastPoint.y, 2)
);
if (distance >= this.sampleDistance) {
this.points.push({ x: event.clientX, y: event.clientY });
this.lastPoint = { x: event.clientX, y: event.clientY };
}
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.moveTo(this.points[0].x, this.points[0].y);
for (let i = 1; i < this.points.length - 2; i++) {
const xc = (this.points[i].x + this.points[i + 1].x) / 2;
const yc = (this.points[i].y + this.points[i + 1].y) / 2;
this.ctx.quadraticCurveTo(this.points[i].x, this.points[i].y, xc, yc);
}
if (this.points.length > 2) {
this.ctx.quadraticCurveTo(
this.points[this.points.length - 1].x,
this.points[this.points.length - 1].y,
this.points[0].x,
this.points[0].y
);
}
this.ctx.stroke();
}
stopDrawing() {
this.isDrawing = false;
this.points = [];
this.lastPoint = null;
}
resize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
}
<div id="demo"></div>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}