Javascript 将矩形对象放在画布的边框上

Javascript 将矩形对象放在画布的边框上,javascript,canvas,border,Javascript,Canvas,Border,我正在制作一个关于弹跳球的程序,当它们颜色相同并且彼此接触时,它们会产生一个新的球。现在,我想在边界的一部分添加一个矩形对象,如果球碰到它,就会破坏球对象。我在画布左右两侧的边界上设置矩形时遇到问题。这是我的代码,我在画布的边界上绘制矩形 function Wall(x,y,width,height) { this.x = x; this.y = y; this.width = width; this.height = height; ctx.strokeStyle = '

我正在制作一个关于弹跳球的程序,当它们颜色相同并且彼此接触时,它们会产生一个新的球。现在,我想在边界的一部分添加一个矩形对象,如果球碰到它,就会破坏球对象。我在画布左右两侧的边界上设置矩形时遇到问题。这是我的代码,我在画布的边界上绘制矩形

function Wall(x,y,width,height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;

  ctx.strokeStyle = 'red';
  ctx.lineWidth = '6';
  ctx.strokeRect(canvas.width/2, 0, canvas.width, 0);   //top, right half
  ctx.strokeRect(-canvas.width/2, canvas.height , canvas.width,0);  //bottom,left half
  ctx.strokeRect(-canvas.width/2, 0, canvas.height/2, 0); //Where i want to border left side, top half, DOESNT WORK

}

我觉得这是我错过的一件非常简单的事情。或者有更好的方法来实现这个概念吗?

我不确定我是否都理解(尤其是为什么使用负坐标),但它应该可以完成以下任务:

ctx.strokeRect(-canvas.width/2, 0, canvas.width, 0)

您需要使用正确的坐标-上角仅为0,0

功能墙(){
让canvas=document.getElementById('myCanvas')
ctx=canvas.getContext('2d')
ctx.strokeStyle=‘红色’;
ctx.lineWidth='6';
ctx.strokeRect(canvas.width/2,0,canvas.width,0);//上半部分,右半部分
ctx.strokeRect(0,canvas.height,canvas.width/2,0);//底部,左半部分
ctx.strokeRect(0,0,0,画布高度/2);
ctx.strokeRect(canvas.width,canvas.height/2,canvas.width,canvas.height);
}
墙()