86 lines
2.3 KiB
JavaScript
86 lines
2.3 KiB
JavaScript
// vim: set ts=2 sw=2 et tw=80:
|
|
class App {
|
|
constructor(conf) {
|
|
if (!(typeof conf === 'object' && conf)) {
|
|
throw new Error('Argument conf different from specification');
|
|
}
|
|
|
|
this.canvas = document.getElementById(conf.canvas);
|
|
if (!this.canvas || this.canvas.tagName !== 'CANVAS') {
|
|
throw new Error(`canvas is not a canvas`);
|
|
}
|
|
|
|
this.ctx = this.canvas.getContext('2d');
|
|
this.favourites = document.querySelector('div#favourites');
|
|
|
|
if (typeof conf.buttons === 'object' && conf.buttons) {
|
|
this.buttons = {}
|
|
for (const b of ['clear', 'button', 'camera'])
|
|
this.buttons[b] = document.getElementById(conf.buttons[b]);
|
|
|
|
if (this.buttons.clear)
|
|
this.buttons.clear.addEventListener('click', () =>
|
|
this.ctx.clearRect(0, 0, canvas.width, canvas.height));
|
|
|
|
if (this.buttons.camera)
|
|
this.buttons.camera.addEventListener('click', () => {
|
|
const base64 = this.canvas.toDataURL();
|
|
const img = document.createElement('img');
|
|
img.src = base64;
|
|
const span = document.createElement('span');
|
|
span.contentEditable = true;
|
|
this.favourites.appendChild(img);
|
|
this.favourites.appendChild(span);
|
|
});
|
|
}
|
|
|
|
this.canvas.addEventListener('mousedown', (e) => {
|
|
this.ctx.save();
|
|
this.ctx.lineWidth = 1;
|
|
this.ctx.moveTo(e.offsetX, e.offsetY);
|
|
this.ctx.beginPath();
|
|
this.mousedown = true;
|
|
});
|
|
|
|
this.canvas.addEventListener('mousemove', (e) => this.mousedown && this.draw(e));
|
|
|
|
const endPath = (e) => {
|
|
if (this.mousedown) {
|
|
this.ctx.lineTo(e.offsetX, e.offsetY);
|
|
this.ctx.stroke();
|
|
this.ctx.restore();
|
|
this.mousedown = false;
|
|
}
|
|
};
|
|
|
|
this.canvas.addEventListener('mouseup', endPath);
|
|
this.canvas.addEventListener('mouseout', endPath);
|
|
|
|
this.strokeStyle = this.constructor.defaultStrokeStyle;
|
|
}
|
|
|
|
static get defaultStrokeStyle() {
|
|
return 'black';
|
|
}
|
|
|
|
get strokeStyle() {
|
|
return this.ctx.strokeStyle;
|
|
}
|
|
|
|
set strokeStyle(style) {
|
|
if (typeof style !== 'string') {
|
|
throw new Error('style is not a string');
|
|
}
|
|
this.ctx.strokeStyle = style;
|
|
}
|
|
|
|
draw(e) {
|
|
console.log(e);
|
|
this.ctx.lineTo(e.offsetX, e.offsetY);
|
|
this.ctx.stroke();
|
|
this.ctx.beginPath();
|
|
this.ctx.moveTo(e.offsetX, e.offsetY);
|
|
}
|
|
}
|
|
|