我想通过javascript创建一个突围游戏。我想知道为什么ctx.clearRect不工作。我想把这个矩形放在y坐标430中,让它显示在画布的底部。当我使用window.setInterval时,它会移动。但是矩形会不断地移动。任何帮助都将不胜感激。对不起,我的英语很差。
var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');
var position = 0;
var yposition = 430;
var length = 80;
var width = 20;
var xSpeed = length*1;
var ySpeed = 0;
function R(){
ctx.fillStyle = "green";
ctx.fillRect(position, yposition, length, width);
};
function C(){
position += xSpeed;
yposition += ySpeed;
};
window.setInterval(() => {
ctx.clearRect(0, 430, length, width);
R();
C();
},150);
ctx.beginPath();
ctx.arc(150, 50, 20, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = "blue";
ctx.fill();发布于 2020-08-26 22:53:50
罪魁祸首是输入到clearRect函数中的参数:
(0, 430, length, width)由于length和width分别是 80 和 20 的硬编码值,因此上面的意思是每次触发intervals回调函数时,它都会在x=0和y=430时清除一个80 x 20像素的矩形区域。
当你的绿色球拍移动时,你实际上是在清理一个你的球拍不再位于的区域。
所以你基本上有两个选择:
第二个看起来有点像这样:
var canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');
var position = 0;
var yposition = 150;
var length = 80;
var width = 20;
var xSpeed = length * 1;
var ySpeed = 0;
function R() {
ctx.fillStyle = "green";
ctx.fillRect(position, yposition, length, width);
}
function C() {
position += xSpeed;
yposition += ySpeed;
}
window.setInterval(() => {
ctx.clearRect(position, yposition, length, width);
C();
R();
}, 500);<canvas id="canvas" width="600" height="400"></canvas>
我绝对建议清除整个画布,因为在画板旁边还会有其他的屏幕对象。
https://stackoverflow.com/questions/63596051
复制相似问题