首页 > 解决方案 > 即使显示尺寸发生变化,如何在 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>

标签: javascripthtmlcsscanvas

解决方案


推荐阅读