简体   繁体   English

Fabric.js canvas 选择位置不正确

[英]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.我正在制作一个网页,我需要能够使用 cursor 在 canvas 上绘制矩形。 I am using Fabric.js to create and manipulate the canvas.我正在使用 Fabric.js 创建和操作 canvas。

The problem I am experiencing is that when selecting on the canvas the selection is not exactly on the cursor position.我遇到的问题是,在 canvas 上选择时,选择并不完全在 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/ 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?如您所见,不需要的偏移量与您为 canvas 选择的边框尺寸可疑地相似,对吧? Seems like it's used in computations of canvas coords inside the Fabric lib.似乎它用于 Fabric lib 中 canvas 坐标的计算。 So I would suggest that you simply don't put any border on your canvas element.因此,我建议您不要在 canvas 元素上放置任何边框。 If you really desire a border, just wrap your canvas with another div and put a border there.如果你真的想要一个边框,只需用另一个 div 包裹你的 canvas 并在那里放一个边框。 Problem solved.问题解决了。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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