繁体   English   中英

使用可调整大小的 canvas 时无法获得正确的鼠标移动 position 或 canvas 高度

[英]Cannot get the correct position of mouse movement or canvas height while using canvas that can be resized

我正在开发一个游戏,我正在努力将图像放置在具有引导列宽的 canvas 的底部。 但它永远不会将 canvas 的真实高度返回给 position canvas 底部的图像。

 <div id="game" class="mt-10">
    <div id="gameContainer" class="container-fluid">
        <svg width="100" height="100">
            <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
        </svg>
        <svg width="100" height="100">
            <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
        </svg> <!-- Give this div your desired background color -->
        <div class="container">
            <div class="row text-center  justify-content-center">
                <div class="col-md-2">
                </div>
                <canvas id="gameArea" class="col-md-8"
                    style="border:1px solid blue !important;padding: 0 !important;margin: 0 !important;">
                </canvas>
                <div class="col-md-2">
                    <button class="btn btn-secondary" id="stopGame">Stop Game</button>

                </div>
            </div>
        </div>
    </div>
</div>

在我的 javascript 代码中,我试图使用下面的代码放置图像。

let canvas = document.getElementById("gameArea");
let ctx = canvas.getContext("2d");
let bowlImage = new Image();
bowlImage.src = 'images/icon.png';
bowlImage.onload = function () {
ctx.drawImage(bowlImage, 0, canvas.getBoundingClientRect().height - 20, 20, 20);
}

但它总是在我看不到的 canvas 之外绘制图像。 当我使用低于 150 的硬编码 y 轴进行测试时,它可以工作。

ctx.drawImage(bowlImage, 0, 120, 20, 20);

我还根据 mousemove 事件移动图像的 position 并使用 evt.clientX - rect.left 或 evt.clientY - rect.top 计算新的 x/y 坐标,这永远不会正确。但是如果我获取 canvas 的高度使用 canvas.getBoundingClientRect().height,它总是超过 150 和 391 左右。不知道我如何得到真正的高度。

canvas。 getBoundingClientRect()根据视口返回值,而不是 canvas 的实际高度和宽度。

要获得 canvas 的实际高度和宽度,只需使用canvas.heightcanvas.width 您可以查看这个问题以帮助理解为什么会这样。

对于鼠标事件,您需要计算百分比来处理 canvas 的大小调整。

例子:

var rect = canvas.getBoundingClientRect();
var widthScale = canvas.width / rect.width;
var heightScale = canvas.height / rect.height;
// where 'e' is the click event
var canvasClickX = (e.clientX - rect.left) * widthScale;
var canvasClickY = (e.clientY - rect.top) * heightScale;

暂无
暂无

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

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