简体   繁体   中英

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: 在此处输入图像描述

And this is what i want: 在此处输入图像描述

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM