Wessel Ottevanger
Wessel Ottevanger

Reputation: 495

Fabric.js canvas selection location incorrect

I am making a webpage where I need to be able to draw rectangles on a canvas with the cursor. I am using Fabric.js to create and manipulate the canvas.

The problem I am experiencing is that when selecting on the canvas the selection is not exactly on the cursor position. This results in it being very difficult to draw the rectangles on the desired locations.

here is a minimal reproductive example:

<html>
<head>
    <style>
        #image_canvas {
            border: 10px solid #efefef;
        }
    </style>
</head>
<body>
    <canvas id="image_canvas"></canvas>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.1.0/fabric.min.js"></script>
    <script>
        var canvas;

        $(document).ready(function () {
            canvas = new fabric.Canvas("image_canvas");
        });
    </script>
</body>
</html>

https://jsfiddle.net/0uc6rLhg/

Here is what happens: enter image description here

And this is what i want: enter image description here

If anyone can tell me what I am doing wrong (or what I'm not doing) I would be very happy!

Upvotes: 1

Views: 295

Answers (1)

Jan Peša
Jan Peša

Reputation: 6980

As you can see, the unwanted offset is suspiciously similar to that border size you chose for the canvas, right? Seems like it's used in computations of canvas coords inside the Fabric lib. So I would suggest that you simply don't put any border on your canvas element. If you really desire a border, just wrap your canvas with another div and put a border there. Problem solved.

.canvas-wrapper {
    border: 10px solid #efefef;
    display: inline-block;
}

Example: https://jsfiddle.net/smajl/2er0kvoq/1

Upvotes: 1

Related Questions