Reputation: 35
I'm making a program that regards bouncing balls, when they are the same color and touch each other they spawn a new ball. Now I want to add a rectangle object on part of the border that if touched by the balls will destroy the ball object. I'm having issues setting rectangles on the border of the left and right side of the canvas. Here is my code where i draw the rectangles on the border of the 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
}
I feel like it's something really simple that I'm missing. Or is there a better way to go about this concept?
Upvotes: 3
Views: 146
Reputation: 92440
You need to use the right coordinates — the top corner is simply 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>
Upvotes: 1
Reputation: 13354
Not sure I've all understood (especially why you use negative coordinates) but it should do the job:
ctx.strokeRect(-canvas.width/2, 0, canvas.width, 0)
Upvotes: 0