当试图制作一个小的游戏引擎时,我很快遇到了一个问题。我正在处理的画布在靠近底部和/或右侧时会拉伸矩形。我环顾四周,似乎找不到其他遇到相同问题的人。我做了一个幻灯片演示来显示问题。 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来调整画布的大小。
最佳答案
fillRect的参数3和4是宽度和高度,而不是坐标
this.canvas.fillRect(x, y, size, size);
https://developer.mozilla.org/de/docs/Web/API/CanvasRenderingContext2D/fillRect
关于javascript - HTML Canvas 内容延伸到底部/右侧,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34042329/