Get boundaries (position) of canvas drawn context lines - javascript

I'm making a little testing thing for physics. I have drawn a circle with lines using canvas and context:
function drawAngles () {
var d = 50; //start line at (10, 20), move 50px away at angle of 30 degrees
var angle = 80 * Math.PI/180;
ctx.beginPath();
ctx.moveTo(300,0);
ctx.lineTo(300,600); //x, y
ctx.moveTo(0,300);
ctx.lineTo(600,300);
ctx.arc(300,300,300,0,2*Math.PI);
ctx.stroke();
}
I want to somehow get the curved boundaries of the circle so I can tell if the ball element has collided.
If I'm testing boundaries on a typical div, I can just do this:
var divCoords= $(".boundingBoxDiv").position();
var top = divCoords.top;
etc...
How do I do this with context lines?
Here's an image... the ball should bounce off of the circle.

Live Demo
This is pretty easy to accomplish, in a radius based collision you just check the distance if the distance is closer than the radius the objects have collided. In this instance we need to do the opposite, if the objects distance is greater than the boundary radius we need to change the angle to keep the objects in.
So first we need to identify our boundary center points, and boundary radius,
var boundaryRadius = 300,
boundaryX = 300,
boundaryY = 300;
Later on in the ball.update method I check against these values.
var dx = boundaryX - this.x,
dy = boundaryY - this.y
We need to get the distance from our ball and the boundaries center point.
dist = Math.sqrt(dx * dx + dy * dy);
Now we need to get the velocity based on our current angle
this.radians = this.angle * Math.PI/ 180;
this.velX = Math.cos(this.radians) * this.speed;
this.velY = Math.sin(this.radians) * this.speed;
Next we check if we are still inside of the boundaries. In this instance if our distance is less than 300 - our own radius (which is 10) so 290, then keep moving.
if (dist < boundaryRadius-this.radius) {
this.x += this.velX;
this.y += this.velY;
Else if our distance is greater than 290, we need to first move back a bit so we aren't colliding, then we just change our heading angle. You can do this in much fancier ways to actual calculate where you should bounce to, in this example I just make it the opposite angle with a tad bit of randomness.
} else {
this.x -= this.velX;
this.y -= this.velY;
this.angle += 180+Math.random()*45;
}
Code in its entirety.
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = 600,
height = 600;
canvas.width = width;
canvas.height = height;
var boundaryRadius = 300,
boundaryX = 300,
boundaryY = 300;
var Ball = function (x, y, speed) {
this.x = x || 0;
this.y = y || 0;
this.radius = 10;
this.speed = speed || 10;
this.color = "rgb(255,0,0)";
this.angle = Math.random() * 360;
this.radians = this.angle * Math.PI/ 180;
this.velX = 0;
this.velY = 0;
}
Ball.prototype.update = function () {
var dx = boundaryX - this.x,
dy = boundaryY - this.y,
dist = Math.sqrt(dx * dx + dy * dy);
this.radians = this.angle * Math.PI/ 180;
this.velX = Math.cos(this.radians) * this.speed;
this.velY = Math.sin(this.radians) * this.speed;
// check if we are still inside of our boundary.
if (dist < boundaryRadius-this.radius) {
this.x += this.velX;
this.y += this.velY;
} else {
// collision, step back and choose an opposite angle with a bit of randomness.
this.x -= this.velX;
this.y -= this.velY;
this.angle += 180+Math.random()*45;
}
};
Ball.prototype.render = function () {
ctx.fillStyle = this.color;
ctx.beginPath();
// draw our circle with x and y being the center
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.px, this.py);
ctx.closePath();
};
var balls = [],
ballNum = 10;
for(var i = 0; i < ballNum; i++){
balls.push(new Ball(boundaryX + Math.random()*30, boundaryY + Math.random() * 30, 5 + Math.random()*15));
}
function drawAngles() {
var d = 50; //start line at (10, 20), move 50px away at angle of 30 degrees
var angle = 80 * Math.PI / 180;
ctx.beginPath();
ctx.moveTo(300, 0);
ctx.lineTo(300, 600); //x, y
ctx.moveTo(0, 300);
ctx.lineTo(600, 300);
ctx.arc(boundaryX, boundaryY, boundaryRadius, 0, 2 * Math.PI);
ctx.strokeStyle = "#000";
ctx.stroke();
}
function render() {
ctx.clearRect(0, 0, width, height);
drawAngles();
balls.forEach(function(e){
e.update();
e.render();
});
requestAnimationFrame(render);
}
render();

Have you looked into ray casting? Also a neat trick for collision detection is to create a new hidden canvas used for collision detection only. You can then draw the circle on to it using only black and white. If the canvas is filled black with a white circle on it you can test collisions by checking the color of a specific pixel at point x. If point x is black the object has collided, if not it hasn't.

Related

How to get coordinates of every circle from this Canvas

I need to create a pattern where 5 circles connected by lines to a middle main circle.
So I have created dynamically by rotating in some certain angle. Now I need each and every circle's x and y axis coordinates for capturing the click events on every circle.
Please help me how to find out of coordinates of every circle?
var canvas, ctx;
function createCanvasPainting() {
canvas = document.getElementById('myCanvas');
if (!canvas || !canvas.getContext) {
return false;
}
canvas.width = 600;
canvas.height = 600;
ctx = canvas.getContext('2d');
ctx.strokeStyle = '#B8D9FE';
ctx.fillStyle = '#B8D9FE';
ctx.translate(300, 250);
ctx.arc(0, 0, 50, 0, Math.PI * 2); //center circle
ctx.stroke();
ctx.fill();
drawChildCircles(5);
fillTextMultiLine('Test Data', 0, 0);
drawTextInsideCircles(5);
}
function drawTextInsideCircles(n) {
let ang_unit = Math.PI * 2 / n;
ctx.save();
for (var i = 0; i < n; i++) {
ctx.rotate(ang_unit);
//ctx.moveTo(0,0);
fillTextMultiLine('Test Data', 200, 0);
ctx.strokeStyle = '#B8D9FE';
ctx.fillStyle = '#B8D9FE';
}
ctx.restore();
}
function drawChildCircles(n) {
let ang_unit = Math.PI * 2 / n;
ctx.save();
for (var i = 0; i < n; ++i) {
ctx.rotate(ang_unit);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,0);
ctx.arc(200, 0, 40, 0, Math.PI * 2);
let newW = ctx.fill();
ctx.stroke();
}
ctx.restore();
}
function fillTextMultiLine(text, x, y) {
ctx.font = 'bold 13pt Calibri';
ctx.textAlign = 'center';
ctx.fillStyle = "#FFFFFF";
// Defining the `textBaseline`…
ctx.textBaseline = "middle";
var lineHeight = ctx.measureText("M").width * 1.2;
var lines = text.split("\n");
for (var i = 0; i < lines.length; ++i) {
// console.log(lines);
if (lines.length > 1) {
if (i == 0) {
y -= lineHeight;
} else {
y += lineHeight;
}
}
ctx.fillText(lines[i], x, y);
}
}
createCanvasPainting();
<canvas id="myCanvas"></canvas>
The problem here is that you are rotating the canvas matrix and your circles are not aware of their absolute positions.
Why don't you use some simple trigonometry to determine the center of your circle and the ending of the connecting lines ?
function lineToAngle(ctx, x1, y1, length, angle) {
angle *= Math.PI / 180;
var x2 = x1 + length * Math.cos(angle),
y2 = y1 + length * Math.sin(angle);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
return {x: x2, y: y2};
}
Ref: Finding coordinates after canvas Rotation
After that, given the xy center of your circles, calculating if a coord is inside a circle, you can apply the following formula:
Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) < r
Ref: Detect if user clicks inside a circle

Multiple Bouncing Balls on Canvas - Javascript

How can you add multiple balls to this code ?
Ideally I would like to send to a function X amount of balls to be displayed on the canvas.
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext("2d");
var p = { x: 25, y: 25 };
var velo = 3,
corner = 50,
rad = 20;
var ball = { x: p.x, y: p.y };
var moveX = Math.cos((Math.PI / 180) * corner) * velo;
var moveY = Math.sin((Math.PI / 180) * corner) * velo;
function DrawMe() {
ctx.clearRect(0, 0, 400, 300);
if (ball.x > canvas.width - rad || ball.x < rad) moveX = -moveX;
if (ball.y > canvas.height - rad || ball.y < rad) moveY = -moveY;
ball.x += moveX;
ball.y += moveY;
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(ball.x, ball.y, rad, 0, Math.PI * 2, false);
ctx.fill();
ctx.closePath();
}
setInterval(DrawMe, 10);
You could have the "DrawMe" function take in the "ball" as a parameter, and instead of just having 1 ball, you could have an array of balls, and on each tick of the "setInterval" call, you could update all of the different balls by looping through the array and calling "DrawMe" for each ball. Just one way :)

Create a collision region on canvas elements That interacts with mouse Events

I want to create a collision region around a canvas element that enables me to interact with that element using mouse events width vanilla javascript.
To elaborate more on my problem here is the following:
at first I make an arc segment constructor with x, y, radius, beginAngle, endAngle, and a color arguments
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
/* arc class constructor */
function ArcSegment(x, y, radius, beginAngle, endAngle, segColor) {
this.x = x;
this.y = y;
this.radius = radius;
this.beginAngle = beginAngle;
this.endAngle = endAngle;
this.segColor = segColor;
this.update = function() {
this.draw();
}
this.draw = function(){
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, this.beginAngle, this.endAngle, false);
ctx.lineWidth = 20;
ctx.strokeStyle = this.segColor;
ctx.stroke();
}
}
Secondly, i add some value to create those arc segments
/* x, y, radius, startAngle, endAngle and color */
var centerX = canvas.width/2;
var centerY = canvas.height/2;
var radiuses = [
100,
120
];
var pi = Math.PI;
var segmentStart = [
pi/2,
0
];
var segmentRotation = [
1.4*pi,
0.2*pi
];
var segmentColors = [
"#133046",
"#15959F"
];
Then, i draw Them on the canvas.
var segment1 = new ArcSegment(centerX, centerY, radiuses[0], segmentStart[0], segmentStart[0]+segmentRotation[0], segmentColors[0]);
segment1.update();
var segment2 = new ArcSegment(centerX, centerY, radiuses[1], segmentStart[1], segmentStart[1]+segmentRotation[1], segmentColors[1]);
segment2.update();
and here is the result:
What i want now is a way to create a collision detection on top of each arc segment created, so when a mouse is clicked or moved on top of that specific arc segment
a sequence of events can occur (like a rotation animation for example or so...).
all the research i've done suggest to get the x and y value of a rectangle and calculate the distance of mouse position (mouse.x, mouse.y) and the length of the rectangle, but that method doesn't work with an arc segment with a lineWidth property.
Any help on the subject would be very appreciated.
Below is a pure mathematical approach, the key here is the code isPointInside
// Classes
function Arc(x, y, angle, arc, radius, colour, highlightColour) {
this.x = x;
this.y = y;
this.angle = angle;
this.arc = arc;
this.radius = radius;
this.colour = colour;
this.highlightColour = highlightColour;
this.highlighted = false;
this.lineWidth = 20;
}
Arc.prototype = {
isPointInside: function(x, y) {
var _x = x - this.x;
var _y = y - this.y;
var distance = Math.sqrt(_x * _x + _y * _y);
var invDistance = 1.0 / distance;
var angle = Math.acos(
_x * Math.cos(this.angle) * invDistance +
_y * Math.sin(this.angle) * invDistance
);
return distance > (this.radius - this.lineWidth/2) &&
distance < (this.radius + this.lineWidth/2) &&
angle < this.arc/2;
},
render: function(ctx) {
ctx.lineWidth = this.lineWidth;
ctx.strokeStyle = this.highlighted ? this.highlightColour : this.colour;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, this.angle - this.arc/2, this.angle + this.arc/2, false );
ctx.stroke();
}
};
// Variables
var canvas = null;
var ctx = null;
var arcs = [];
// Functions
function draw() {
ctx.fillStyle = "gray";
ctx.fillRect(0, 0, 999, 999);
for (var i = 0; i < arcs.length; ++i) {
arcs[i].render(ctx);
}
}
// Event Listeners
function onMouseMove(e) {
var bounds = canvas.getBoundingClientRect();
var x = e.clientX - bounds.left;
var y = e.clientY - bounds.top;
for (var i = 0; i < arcs.length; ++i) {
arcs[i].highlighted = arcs[i].isPointInside(x, y);
}
draw();
}
// Entry Point
onload = function() {
canvas = document.getElementById("canvas");
canvas.onmousemove = onMouseMove;
ctx = canvas.getContext("2d");
arcs.push(new Arc(190, 75, 0.2, 1.8, 60, "blue", "lime"));
arcs.push(new Arc(90, 75, 3.5, 4.2, 60, "red", "lime"));
draw();
}
<canvas id="canvas"></canvas>

Canvas beginPath() is not clearing rect before each frame

I want to animate a rect on a canvas. It technically works, but the canvas is not clearing before each frame and it leaves a mark on the ground (sort of like a snail). I have done research and everything seems to point to the use of ctx.beginPath() as the solution to my problem, but when I try to use it here, it doesn't work. What am I doing wrong?
Here is the raw javascript:
// create a canvas element
var canvas = document.createElement("canvas");
// attach element to DOM
document.getElementsByTagName("body")[0].appendChild(canvas);
// get the canvas context (this is the part we draw to)
var ctx = canvas.getContext("2d");
var bug = new Bug(0,0);
function setup() {
// setup the canvas size to match the window
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// set the 0,0 point to the middle of the canvas
ctx.translate(canvas.width / 2, canvas.height / 2);
}
function draw() { //Do the drawing
ctx.beginPath();
bug.update();
bug.draw();
window.requestAnimationFrame(function(){draw()});
}
// start enterFrame loop
window.requestAnimationFrame(draw);
// force running setup
setup();
// re-setup canvas when the size of the window changes
window.addEventListener("resize", setup);
// sin(pi) == 0
// cos(pi) == -1
// sin(2pi) == 0
// cos(2pi) == 1
// degrees to radians: {{ deg * (pi/180) = rad }}
function randomRange(max, min) {
return Math.floor(Math.random() * (max - min) + min);
}
function Bug(x, y) {
this.x = x;
this.y = y;
this.jitter = 10;
this.speed = 1;
this.deg = 0;
this.rad = 0;
this.update = function() {
//update degrees
this.deg += randomRange(this.jitter, -this.jitter);
//convert degrees into radians
this.rad = this.deg * (Math.PI/180);
//update coordinates
this.x += this.speed * (Math.cos(this.rad));
this.y += this.speed * (Math.sin(this.rad));
};
this.draw = function() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fill();
};
}
The beginPath function doesn't clear the screen it starts a path to draw, to clear the screen you should use clearRect instead and in your specific situation you should use:
ctx.clearRect(-canvas.width, -canvas.height, canvas.width*2, canvas.height*2);

Canvas bouncing balls showing an elliptical black ball

JSFiddle
Intended behavior
Sample values: Velocity: 10; Angle: 45; Color: red; Radius: 50.
On clicking "Shoot!" button, ball should move until it finally disappears behind one of the walls. Note that I want to simulate real world ball with gravity.
Each time we click Shoot, one more ball should be added to the balls array which will also be drawn.
What happens
A black ellipse is shown on clicking shoot once/multiple time. No console errors seen.
Code:
(function () {
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d"),
WIDTH = canvas.width,
HEIGHT = canvas.height;
// our ball object
function Ball(radius, color) {
this.radius = radius;
this.color = color;
this.x = 50; // start coordinates
this.y = 50;
this.velX = 0;
this.velY = 0;
this.accX = 0;
this.accY = 0;
this.gravity = 0;
this.start = function (angle, velocity) {
this.gravity = 9.8;
this.angle = angle / 180 * Math.PI; // convert to radians
this.velX = velocity * Math.cos(this.angle);
this.velY = velocity * Math.sin(this.angle);
this.accX = 0; // zero intially
this.accY = 0; // TODO: set option for user to set himself
};
this.update = function () {
this.velY -= this.gravity;
};
this.draw = function () {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.fillSyle = this.color;
ctx.fill();
ctx.closePath();
}
}
// balls array
var balls = [];
document.querySelector("input[type='button']").onclick = function () {
var color = gId("color").value, // getElementById; defined in jsfiddle
velocity = gId("velocity").value,
angle = gId("angle").value,
radius = gId("radius").value;
var ball = new Ball(radius, color);
ball.start(angle, velocity);
balls.push(ball);
};
setInterval(function () {
for (var i = 0, len = balls.length; i < len; i++) {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
balls[i].draw();
balls[i].update();
}
}, 1000 / 60); // 1000/x depicts x fps
I have no idea why it doesn't work. System: Windows 7 on Chrome/Firefox latest.
Any help is appreciated. Please comment for more information.
1) Set width and height attributes on your canvas element instead of applying a css style i.e:
<canvas width="400px" height="400px">You don't support canvas.</canvas>
2) divide the value of gravity by 60 because your update function is invoked every 1/60th of a second i.e:
this.start = function (angle, velocity) {
this.gravity = 9.8 / 60;
this.angle = angle / 180 * Math.PI; // convert to radians
this.velX = velocity * Math.cos(this.angle);
this.velY = velocity * Math.sin(this.angle);
this.accX = 0; // zero intially
this.accY = 0; // TODO: set option for user to set himself
};
3) change the update function to:
this.update = function () {
this.velY += this.gravity;
this.x += this.velX;
this.y += this.velY;
};
4) move the ctx.clearRect method outside the for loop otherwise you will only see one ball animating always i.e
setInterval(function () {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i = 0, len = balls.length; i < len; i++) {
balls[i].draw();
balls[i].update();
}
}, 1000 / 60); // 1000/x depicts x fps
Here the updated js-fiddle: http://jsfiddle.net/km6ozj6L/1/

Categories

Resources