javascript - 即使显示尺寸发生变化,如何在 html 画布中获得精确坐标
问题描述
问题:我想用随机的 x,y 坐标绘制一个矩形(使用 fillRect)。坐标应在用户可见范围内。现在,当我尝试使用 getBoundingClientRect() 获取窗口的宽度和高度时,但是当我在返回的坐标内绘制一个矩形时,该矩形不在用户的可见范围内。请帮助我如何让它正常工作
const score_elem = document.getElementById('score');
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
var width = canvas.getBoundingClientRect().width;
var height = canvas.getBoundingClientRect().height;
initial_time = 1;
decrease_factor = 0.1;
current_time = initial_time;
button_size = 50; /* in px */
console.log(width, height)
x = Math.floor(Math.random() * (width - button_size));
y = Math.floor(Math.random() * (height - button_size));
while (ctx.isPointInPath(x, y)) {
x = Math.floor(Math.random() * (width - button_size));
y = Math.floor(Math.random() * (height - button_size));
}
console.log("first cor", x, y)
function game() {
ctx.fillStyle = 'blue';
ctx.fillRect(x, y, button_size, button_size);
current_time -= decrease_factor;
while (ctx.isPointInPath(x, y)) {
x = Math.floor(Math.random() * 100);
y = Math.floor(Math.random() * 100);
}
console.log("second cor", x, y);
}
function clear() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
game();
ctx.fillStyle = 'red';
ctx.fillRect(250, 0, button_size, button_size);
canvas {
width: 100%;
height: 00px;
background-color: black;
}
body {
background: #00ff00;
}
<h1>Reactions Game</h1>
<canvas id="game"></canvas>
<p>Click/tap the boxes as you see them</p>
<h3 id="score"></h3>
<script src="./app.js"></script>
解决方案
推荐阅读
- python - 设置可变数量的热键监听器 pynput
- debian - 如何在旧的 Debian 中编译 Cairo
- sql - 通过加入它们来更新多个表中的不同列
- automation - 我可以在我的桌面上找到项目的坐标吗?
- scala - 将 for 理解嵌套在 yield 中
- hadoop - mapreduce 文件传输实现
- winforms - 显示和隐藏面板(Powershell GUI)
- ios - Flutter IOS Distribution 失败并出现错误
- google-analytics - Google Analytics(分析)中用于将转化归因于不同会话的渠道的默认时间段是多少?
- python - 试图让用户选择一个选项,但它不起作用