当试图制作一个小游戏引擎时,我很快就遇到了问题。我正在处理的画布在靠近底部和/或右边时拉伸矩形。我环顾四周,似乎无法找到其他人遇到同样的问题。我做了一个滑块演示来显示问题。
http://codepen.io/Magnesium/pen/wMwwgx
我将在下面列出最有可能出现问题的代码。
var engine = function(canvas) { // Trying to make a game engine when the problems started
this.canvas = canvas.getContext("2d");
this.defaultColor = "#FF0000";
this.clearCanvas = function() { // Clears canvas
this.canvas.clearRect(0, 0, canvas.width, canvas.height);
};
this.square = function(x, y, size, color) { // Makes a square. I don't see any problems, but if the error is caused by me it would probably be here
if (color == undefined) color = this.defaultColor;
this.canvas.fillStyle = color;
this.canvas.fillRect(x, y, x + size, y + size);
};
}
使用它的代码
setInterval(function() { // Called ~30 times a second
enjin.clearCanvas();
enjin.square(parseInt(rangeX.value), parseInt(rangeY.value), parseInt(size.value));
}, 30);
注意:这个问题很可能不是由于CSS调整画布大小造成的,原因有两个,其中一个原因是我没有使用CSS来调整画布大小。
答案 0 :(得分:2)
fillRect的参数3和4是宽度和高度,而不是坐标
this.canvas.fillRect(x, y, size, size);
https://developer.mozilla.org/de/docs/Web/API/CanvasRenderingContext2D/fillRect