首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >画布问题。( ctx.clearRect不工作)

画布问题。( ctx.clearRect不工作)
EN

Stack Overflow用户
提问于 2020-08-26 18:52:51
回答 1查看 36关注 0票数 0

我想通过javascript创建一个突围游戏。我想知道为什么ctx.clearRect不工作。我想把这个矩形放在y坐标430中,让它显示在画布的底部。当我使用window.setInterval时,它会移动。但是矩形会不断地移动。任何帮助都将不胜感激。对不起,我的英语很差。

代码语言:javascript
复制
 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();
EN

回答 1

Stack Overflow用户

发布于 2020-08-26 22:53:50

罪魁祸首是输入到clearRect函数中的参数:

代码语言:javascript
复制
(0, 430, length, width)

由于lengthwidth分别是 80 20 的硬编码值,因此上面的意思是每次触发intervals回调函数时,它都会在x=0和y=430时清除一个80 x 20像素的矩形区域。

当你的绿色球拍移动时,你实际上是在清理一个你的球拍不再位于的区域。

所以你基本上有两个选择:

  1. 清除整个画布每一帧
  2. 在更改位置之前清除您的划板所在的屏幕区域

第二个看起来有点像这样:

代码语言:javascript
复制
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);
代码语言:javascript
复制
<canvas id="canvas" width="600" height="400"></canvas>

我绝对建议清除整个画布,因为在画板旁边还会有其他的屏幕对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63596051

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档