简体   繁体   English

无法在画布上绘制正方形

[英]can't draw square on canvas

hey guys I'm starting a snake game in JavaScript.嘿伙计们,我正在用 JavaScript 开始玩蛇游戏。 Right now I'll I'm trying to do is paint a little green square in the center of the canvas.现在我要做的是在画布的中心画一个绿色的小方块。 I've set the fillStyle and used the fillRect method, but I get nothing.我已经设置了 fillStyle 并使用了 fillRect 方法,但我什么也没得到。 Could somebody explain the issue, I'd really appreciate it, thanks:)有人可以解释这个问题吗,我真的很感激,谢谢:)

 const canvas = document.querySelector('#canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'limegreen'; ctx.fillRect(375, 250, 10, 10);
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Snake Game</title> <style> body { background-color: #333; } canvas { background-color: #4d4d4d; margin: auto; display: block; position: absolute; left: 0; right: 0; top: 0; bottom: 0; width: 750px; height: 500px; } </style> </head> <body> <canvas id="canvas"></canvas> <script src="script.js"></script> </body> </html>

It looks like the dimensions of your canvas are too small (ie the default dimensions of 300w x 150h) meaning that the green rectangle is drawn at [375,250] which is outside of the canvas' dimensions.看起来画布的尺寸太小(即默认尺寸为 300w x 150h),这意味着绿色矩形绘制在 [375,250] 处,超出了画布的尺寸。

Try setting the width and height attributes of the canvas (ie to match your styles) as follows:尝试设置画布的widthheight属性(即匹配您的样式),如下所示:

canvas.width = 750;
canvas.height = 500;

This will ensure that the canvas resolution/dimensions are appropriatly set causing the rectangle to be visible.这将确保正确设置画布分辨率/尺寸,从而使矩形可见。

The key take away: the canvas has it's own concept of dimensions.关键在于画布有自己的尺寸概念。 These are not inherited from any CSS styling that is applied to the canvas.这些不是从应用于画布的任何 CSS 样式继承的。

Here's a working snippet:这是一个工作片段:

 const canvas = document.querySelector('#canvas'); const ctx = canvas.getContext('2d'); // Necessary to specify the resolution of the canvas // explicitly by doing this: canvas.width = 750; canvas.height = 500; ctx.fillStyle = 'limegreen'; ctx.fillRect(375, 250, 10, 10);
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Snake Game</title> <style> body { background-color: #333; } canvas { background-color: #4d4d4d; margin: auto; display: block; position: absolute; left: 0; right: 0; top: 0; bottom: 0; width: 750px; height: 500px; } </style> </head> <body> <canvas id="canvas"></canvas> <script src="script.js"></script> </body> </html>

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

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