Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't scale or rotate fabricJs Image, Rect, Ellipse

As in the title, I'm using fabricJS 4.6.0 with VueJs 3.

I'm trying to simply setup fabric with resizable rectangles.

My problem is accessing the object canvas outside the initFabric method.

I can't resize or rotate the rectangle, just move it.

The only way to make it works is declare canvas as const if I use this.canvas doesn't work.

here the jsfiddle https://jsfiddle.net/8vzc3bj5/19/

initFabric: function () {
    var canvasEl = this.$refs.canvas;
    canvasEl.width = 1920;
    canvasEl.height = 1080;

    const canvas = new fabric.Canvas(canvasEl, {
        // isDrawingMode: true,
        centeredScaling: true,
        backgroundColor: "#fff",
        selectionBorderColor: "rgba(255, 255, 255, 0.8)",
        selectionColor: "rgba(255, 255, 255, 0.8)",
        selectionLineWidth: 2,
        borderColor: "gray",
        cornerColor: "black",
        cornerSize: 12,
        transparentCorners: true,
    });

    canvas.on("selection:created", this.handleSelection);
    canvas.on("selection:updated", this.handleSelection);

    canvas.on("after:render", this.updateCanvas);
    canvas.on("object:modified", this.updateCanvas);
    canvas.on("object:added", this.updateCanvas);
    canvas.on("object:removed", this.updateCanvas);

    canvas.on("mouse:wheel", (opt) => {
        var delta = opt.e.deltaY;
        var zoom = canvas.getZoom();
        zoom *= 0.999 ** delta;
        if (zoom > 20) zoom = 20;
        if (zoom < 0.01) zoom = 0.01;
        canvas.zoomToPoint(
            { x: opt.e.offsetX, y: opt.e.offsetY },
            zoom
        );
        opt.e.preventDefault();
        opt.e.stopPropagation();
    });

    this.$nextTick(() => {
        var rect = new fabric.Rect({
            left: 100,
            top: 50,
            fill: "yellow",
            width: 200,
            height: 100,
            stroke: "lightgreen",
            strokeWidth: 4,
            zoomX: 1,
            zoomY: 1,
            dirty: true,
        });
        canvas.add(rect);
        rect.center();
        canvas.setActiveObject(rect);
        canvas.bringToFront(rect);
        canvas.renderAll();
    });
    this.resizeCanvas();
},

Thanks

like image 396
Angus Simons Avatar asked Nov 02 '25 17:11

Angus Simons


1 Answers

Fabricjs does not like having the canvas converted to a proxy. One way to get around it is to use a global variable instead of using the data. You can also just remove canvas from the data() declaration, which will make it still accessible throughout the template and code, but not make it reactive.

See original post Fabricjs, selection handles shown but not clickable before selected together with other shapes

like image 195
Boki Avatar answered Nov 04 '25 05:11

Boki