Canvas.js

99 lines | 2.738 kB Blame History Raw Download


//Обертка над элементом Canvas для удобства работы
class Canvas {

    constructor(CanvasElem) {
        this.canvas = CanvasElem;
        this.context = this.canvas.getContext("2d");

        this._IsDrawing = false;
    }

    //Вкл/Выкл рисование пользователю
    Set_UserWrite(CanWrite) {

        if (CanWrite) {

            this.canvas.onmousedown = this._StartDrawing.bind(this);
            this.canvas.onmouseup = this._StopDrawing.bind(this);
            this.canvas.onmouseout = this._StopDrawing.bind(this);
            this.canvas.onmousemove = this._Draw.bind(this);
        }
        else {
            this._IsDrawing = false;

            this.canvas.onmousedown = null;
            this.canvas.onmouseup = null;
            this.canvas.onmouseout = null;
            this.canvas.onmousemove = null;
        }
    }

    //Нарисовать тестовую линию
    PrintLine() {
        //this.context.moveTo(0, 0);
        //this.context.lineTo(200, 100);
        //this.context.stroke();
    }

    //Очистить
    ClearCanvas() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }

    //Изменить цвет пера
    ChangeColor(color) {

        this.context.strokeStyle = color;
    }

    //Изменить толщину пера
    ChangeThickness(thickness) {

        this.context.lineWidth = thickness;
    }

    //Получить рендер текущего изображения в формате base64
    GetImage(format) {
        return this.canvas.toDataURL(format);
    }

    //
    DrawImage(image, width, height) {
        this.context.drawImage(image, 0, 0, width, height);
    }


    //Private
    //Методы рисования пользователя
    // -------------

    _StartDrawing(e) {
        // Начинаем рисовать
        this._IsDrawing = true;

        // Создаем новый путь (с текущим цветом и толщиной линии) 
        this.context.beginPath();

        // Нажатием левой кнопки мыши помещаем "кисть" на холст
        this.context.moveTo(e.pageX - this.canvas.offsetLeft, e.pageY - this.canvas.offsetTop);
    }

    _Draw(e) {
        if (this._IsDrawing == true) {
            // Определяем текущие координаты указателя мыши
            let x = e.pageX - this.canvas.offsetLeft;
            let y = e.pageY - this.canvas.offsetTop;

            // Рисуем линию до новой координаты
            this.context.lineTo(x, y);
            this.context.stroke();
        }
    }

    _StopDrawing() {
        this._IsDrawing = false;
    }

}