将矩形对象放在 canvas 的边框上
Putting rectangle object on border of canvas
我正在制作一个关于弹跳球的程序,当它们颜色相同并相互接触时,它们会产生一个新球。现在我想在边界的一部分上添加一个矩形对象,如果被球触及,就会破坏球对象。我在 canvas 左右边界上设置矩形时遇到问题。这是我的代码,我在 canvas.
的边界上绘制矩形
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。
function Wall() {
let canvas = document.getElementById('myCanvas')
ctx = canvas.getContext('2d')
ctx.strokeStyle = 'red';
ctx.lineWidth = '6';
ctx.strokeRect(canvas.width/2, 0, canvas.width, 0); //top, right half
ctx.strokeRect(0, canvas.height , canvas.width/2,0); //bottom,left half
ctx.strokeRect(0, 0, 0, canvas.height/2);
ctx.strokeRect(canvas.width, canvas.height/2, canvas.width, canvas.height);
}
Wall()
<canvas id="myCanvas"></canvas>
我正在制作一个关于弹跳球的程序,当它们颜色相同并相互接触时,它们会产生一个新球。现在我想在边界的一部分上添加一个矩形对象,如果被球触及,就会破坏球对象。我在 canvas 左右边界上设置矩形时遇到问题。这是我的代码,我在 canvas.
的边界上绘制矩形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。
function Wall() {
let canvas = document.getElementById('myCanvas')
ctx = canvas.getContext('2d')
ctx.strokeStyle = 'red';
ctx.lineWidth = '6';
ctx.strokeRect(canvas.width/2, 0, canvas.width, 0); //top, right half
ctx.strokeRect(0, canvas.height , canvas.width/2,0); //bottom,left half
ctx.strokeRect(0, 0, 0, canvas.height/2);
ctx.strokeRect(canvas.width, canvas.height/2, canvas.width, canvas.height);
}
Wall()
<canvas id="myCanvas"></canvas>