如何获取Canvas实际单位尺寸,避免Wolf与Deer移出画布?
It looks like your main goal is to correctly get the actual displayed dimensions of your canvas (styled with width:100%; height:100%) to keep your wolves and deer from moving outside the visible area. Let's break down the fixes you need:
First, the canvas.length property you’re using doesn’t exist—you probably intended to reference the canvas’s width, but even canvas.width refers to the internal drawing buffer size, not the actual size the canvas is displayed on the page. To get the rendered dimensions, use canvas.clientWidth and canvas.clientHeight instead.
Second, your movement boundary check has a logic error: you’re using && (requiring all conditions to be true) when you should use || (triggering if any condition is true) to detect if the new position is outside the canvas. Here’s how to fix that section:
if(this.nearbyPredators.length == 0){ // If there are no nearby prey, move randomly if(this.nearbyPrey.length === 0){ var tx = this.x + getRandomInt(-8,9); var ty = this.y + getRandomInt(-9,8); // Fixed boundary check using client dimensions and correct logic while(tx <= this.size || ty <= this.size || tx >= canvas.clientWidth - this.size || ty >= canvas.clientHeight - this.size){ tx = this.x + getRandomInt(-8,9); ty = this.y + getRandomInt(-9,8); } this.x = tx; this.y = ty; // ... rest of your movement logic }
This checks if the new position is too far left (≤ animal size), too far right (≥ canvas width minus animal size), too far up (≤ animal size), or too far down (≥ canvas height minus animal size). If any of these are true, it generates a new random position until a valid one is found.
If you also want your canvas’s drawing buffer to match the displayed size (so your animals look crisp instead of stretched), add this code after initializing the canvas:
function resizeCanvas() { canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; } // Set initial size resizeCanvas(); // Optional: Update size when window is resized window.addEventListener('resize', resizeCanvas);
This ensures the canvas’s internal resolution matches its displayed size, preventing blurry rendering while still giving you the correct bounds for animal movement.
内容的提问来源于stack exchange,提问作者Electrox Qui Mortem

