當試圖製作一個小遊戲引擎時,我遇到了一個問題很快。我正在處理的畫布在接近底部和/或右側時延伸矩形。我環顧四周,似乎無法找到其他人遇到同樣問題的人。我做了一個滑塊演示來展示這個問題。
http://codepen.io/Magnesium/pen/wMwwgx
我將包含最有可能存在以下問題的代碼。
HTML帆布東西伸展到底部/右邊
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來調整畫布的大小。
'this.canvas.fillRect(X,Y,X +大小,Y +大小);'你將x和y值添加到'fillRect()'寬度和高度參數。你的代碼中的一切都是正常的。 – Kaiido