write_picture
Version:
"Una librería de dibujo a mano libre sobre canvas con fondo de imagen.
79 lines (62 loc) • 2.13 kB
JavaScript
export class WriteImage {
constructor({ canvas, imageUrl, color, lineWidth }) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
this.imageUrl = imageUrl;
this.drawing = false;
this.color = color || '#ff0000';
this.lineWidth = lineWidth || 5;
// Cargar la imagen de fondo
this.image = new Image();
if (this.imageInput.startsWith('data:image')) {
image.src = this.imageInput; // Es Base64
} else {
image.src = this.imageInput; // Es URL
}
this.addEventListeners();
}
startDrawing(e) {
this.drawing = true;
this.draw(e);
}
stopDrawing() {
this.drawing = false;
this.ctx.beginPath();
}
setSize(number) {
this.lineWidth = number;
}
draw(e) {
if (!this.drawing) return;
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
this.ctx.lineWidth = this.lineWidth;
this.ctx.lineCap = 'round';
this.ctx.strokeStyle = this.color;
this.ctx.lineTo(x, y);
this.ctx.stroke();
this.ctx.beginPath();
this.ctx.moveTo(x, y);
}
// Método para cambiar el color del lápiz
setColor(newColor) {
this.color = newColor;
}
// Método para borrar los dibujos, pero manteniendo la imagen de fondo
clearCanvas() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.drawImage(this.image, 0, 0, this.canvas.width, this.canvas.height);
}
// Método para descargar la imagen con los dibujos
getImage() {
return this.canvas.toDataURL('image/png');
}
// Agregar los event listeners
addEventListeners() {
// Evento para dibujar
this.canvas.addEventListener('mousedown', (e) => this.startDrawing(e));
this.canvas.addEventListener('mouseup', () => this.stopDrawing());
this.canvas.addEventListener('mousemove', (e) => this.draw(e));
}
}