write_in_picture
Version:
"Una librería de dibujo a mano libre sobre canvas con fondo de imagen.
82 lines (65 loc) • 2.29 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();
this.image.src = this.imageUrl;
this.image.onload = () => {
this.ctx.drawImage(this.image, 0, 0, this.canvas.width, this.canvas.height);
};
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
downloadImage() {
const dataURL = this.canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = dataURL;
link.download = 'imagen_con_dibujo.png';
link.click();
}
// 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));
}
}