Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.8 kB
0
Indexable
Never
import { fabric } from 'fabric';

window.initFabricCanvas = function (artworkUrl, livewireComponent) {
    return {
        artworkUrl,
        livewireComponent,
        init() {
            this.canvas = new fabric.Canvas('blushCanvas');
            this.loadArtwork();
            this.setupCanvasInteractions();
        },

        loadArtwork() {
            fabric.Image.fromURL(this.artworkUrl, img => {
                this.canvas.setBackgroundImage(img, this.canvas.renderAll.bind(this.canvas), {
                    scaleX: this.canvas.width / img.width,
                    scaleY: this.canvas.height / img.height
                });
            });
        },

        setupCanvasInteractions() {
            this.canvas.isDrawingMode = true;
            this.canvas.freeDrawingBrush.width = 10;
            this.canvas.freeDrawingBrush.color = 'white';

            document.getElementById('brushSize').addEventListener('input', e => {
                this.canvas.freeDrawingBrush.width = parseInt(e.target.value, 10);
            });

            document.getElementById('reset').addEventListener('click', () => {
                this.resetCanvas();
            });

            document.getElementById('undo').addEventListener('click', () => {
                this.undoLastAction();
            });

            document.getElementById('save').addEventListener('click', () => {
                this.saveDrawing();
            });
        },

        resetCanvas() {
            this.canvas.clear();
            this.loadArtwork();
        },

        undoLastAction() {
            const lastObject = this.canvas.getObjects().pop();
            if (lastObject) {
                this.canvas.remove(lastObject);
                this.canvas.renderAll();
            }
        },

        saveDrawing() {
            const grayBackground = new fabric.Rect({
                left: 0,
                top: 0,
                fill: 'gray',
                width: this.canvas.width,
                height: this.canvas.height
            });
            this.canvas.add(grayBackground);
            this.canvas.sendToBack(grayBackground);
            this.canvas.renderAll();

            const dataURL = this.canvas.toDataURL({
                format: 'png',
                quality: 1.0,
                left: 0,
                top: 0,
                width: this.canvas.width,
                height: this.canvas.height,
                multiplier: 1
            });




            return;
            Livewire.find(this.livewireComponent).set('photoMask', dataURL);
            Livewire.find(this.livewireComponent).set('open', false);

            this.canvas.remove(grayBackground);
            this.canvas.renderAll();
        },


    };
};
Leave a Comment