【问题标题】:Gap between cursor and drawing on canvas光标和画布上的绘图之间的间隙
【发布时间】:2019-12-13 11:40:08
【问题描述】:

我被一个问题困扰了好几天,似乎找不到解决方案。光标和绘图之间有间隙,我不知道如何修复它。 我已经在 HTML 而不是 CSS 文件中设置了画布的高度/宽度,我尝试了不同的方法来获取光标位置并添加/删除一些像素来纠正 lineTo 线上的间隙,但它没有不要改变任何东西。 有关信息,我的画布位于宽度为 40% 的容器中的地图旁边,我不知道这是否是问题,但我不想更改它。

class Canvas {
    constructor(canvasId) {
        this.canvas = canvasId;
        this.ctx = this.canvas.getContext('2d');
        this.signing = false;
    }

    load() {
        this.start();
        this.draw();
        this.stop();

    }

    start() {
        this.canvas.addEventListener('mousedown', () => {
            this.signing = true;
            const rectangle = this.canvas.getBoundingClientRect(e);
            this.ctx.moveTo(e.clientX - rectangle.left, e.clientY - rectangle.top);
            this.beginPath();
        });
    }
    stop() {
        this.canvas.addEventListener('mouseup', () => {
            this.signing = false;
            this.ctx.beginPath();
        });
    }
    draw() {
        this.canvas.addEventListener('mousemove', (e) => {
            if (this.signing === true) {
                this.ctx.lineWidth = '2';
                this.ctx.lineCap = "round";

                this.ctx.lineTo(e.clientX - this.canvas.offsetLeft - 65, e.clientY - this.canvas.offsetTop - 40);
                this.ctx.stroke();
            }
        });
    }
};

const signature = new Canvas(document.getElementById('to-sign'));
signature.load();
canvas {
    border: solid; 
}
<canvas id="to-sign" class="full-width" width="620" height="160">
Non supporté sur votre navigateur
</canvas>

【问题讨论】:

  • 你能给我们一个minimal, complete, and verifiable example吗?我已经编辑了您的答案并将您的代码转换为演示 sn-p。你能编辑那个 sn-p 并让它工作吗?这将有助于我们调试您的问题。
  • 我在这里工作时遇到了麻烦,我是 JavaScript 和 stackoverflow 的新手......所以我编辑了代码以使其显示,实际上由于差距而没有显示。我收集鼠标位置的方式肯定有问题,但我尝试的一切都存在差距。

标签: javascript canvas


【解决方案1】:

如果您的画布上有填充,则会出现此问题。 getBoundingClientRect 返回元素边框的位置和大小。这包括填充。请参阅此Introduction to the CSS Box Model 和此参考getBoundingClientRect

【讨论】:

  • 据我了解,画布上的边框可能是一个问题,因为它添加了一些填充。如果我错了,我会不断通知自己。我将画布插入一个 div 并在那里设置边框,间隙更小但它仍然存在。至少有一些变化,谢谢你的回答!
猜你喜欢
  • 2018-11-19
  • 2016-01-09
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
相关资源
最近更新 更多