【问题标题】:Why are the rectangles I am creating on this canvas not getting put in the right spot?为什么我在此画布上创建的矩形没有放在正确的位置?
【发布时间】:2015-10-15 20:30:36
【问题描述】:

我正在尝试创建一个简单的页面,您可以在其中单击并在画布上创建矩形。它将用户的鼠标单击作为输入,然后从单击的 x 和 y 创建一个矩形。但是,它会将矩形偏向一边,我不知道为什么。

小提琴:https://jsfiddle.net/2717s53h/

HTML

<canvas id="cnv"></canvas>

CSS

#cnv{
    width:99vw;
    height:98vh;
    background-color:#faefbd;
}

JAVASCRIPT

$(function () {
    var canvas = $('#cnv');
    var canvObj = document.getElementById('cnv');
    var ctx = canvObj.getContext('2d');

    var point1 = {};
    var point2 = {};

    canvas.click(function (e) {
        console.log(e);

        var x = e.pageX;
        var y = e.pageY;

        console.log(x);
        console.log(y);

        if (Object.keys(point1).length == 0)
        {
            point1.x = x;
            point1.y = y;
        }
        else if (Object.keys(point2).length == 0)
        {
            point2.x = x;
            point2.y = y;

            console.log(point1);
            console.log(point2);
            var width = point2.x - point1.x;
            var height = point2.y - point1.y;
            width = width < 0 ? width * -1 : width;
            height = height < 0 ? height * -1 : height;
            ctx.fillRect(x, y, 10, 10);

            point1 = {};
            point2 = {};
        }

    });
});

【问题讨论】:

标签: javascript jquery html canvas


【解决方案1】:

CSS的height/width和HTML的canvas属性height和width是有区别的:前者定义了canvas在页面中占据的空间;后者定义了渲染表面。具体来说,假设您有以下画布:

<canvas height="400" width="600"></canvas>

具有 1200x800 大小的视口并且画布的 CSS 设置为 width: 100%; height: 100%;,然后您的画布将呈现为 拉伸两倍大并且在高度和宽度上都模糊(例如在你的小提琴中;显然这些矩形大于 10px)。因此,页面坐标与画布坐标不同步

根据specification,您的小提琴的画布渲染表面是 300x150,因为您没有指定宽度/高度属性:

width属性默认为300,height属性默认为150。

查看your fiddle 的略微“修正”版本。

因此,我的建议(作为 HTML-canvas 的非专家)是始终指定这 2 个属性,并且不要混淆不同的渲染表面和显示尺寸(当然不是相对的)像 vw, vh, %, em, ...) 如果你不想要不可预测的结果;虽然有些 SO 用户一直在寻找a solution

【讨论】:

    猜你喜欢
    • 2022-10-21
    • 1970-01-01
    • 2019-04-18
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多