I would like to point out that I'm a beginner at this. So please, I hope you don't mind me asking questions to your solutions.
What I'm trying to construct here is a graphical animation of a ball falling to the ground from a height and then slowly, after several subsequent bounces, the ball just rolls on the base of the canvas.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JavaScript examples</title>
<!-- As a shortcut, I included style information here rather than a separate file -->
<style>
canvas {
border: 1px solid gray;
}
</style>
<!-- incorporate jQuery -->
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<!-- now my written script -->
<script>
$(function(){
// initialise canvas and context
var canvas = document.getElementById('canvas');
// physical variables
var g = 0.1; // gravity
var fac = 0.8; // velocity reduction factor per bounce
var radius = 20; // ball radius
var color = "#0000ff"; // ball color
var intervalId
function initBall() {
// initialise position and velocity of ball
var x = 50;
var y = 50;
var horizontalvelocity = 2;
var verticalvelocity = 0;
}
function drawBall() {
with (context){
clearRect(0, 0, canvas.width, canvas.height); // clear canvas
fillStyle = color;
beginPath();
arc(x, y, radius, 0, 2*Math.PI, true);
closePath();
fill();
};
};
function render() {
// update velocity
verticalvelocity += g; // gravity
// update position
x += horizontalvelocity;
y += verticalvelocity;
// handle bouncing
if (y > canvas.height - radius){
y = canvas.height - radius;
verticalvelocity *= -fac;
}
// wrap around
if (x > canvas.width + radius){
x = -radius;
}
// update the ball
drawBall();
};
function init() {
<!-- get the rendering area for the canvas -->
context = $('#canvas')[0].getContext("2d");
WIDTH = $('#canvas').width();
HEIGHT = $('#canvas').height();
setInterval(update, 1000/60); // 60 frames per second
initBall();
<!-- start animation -->
intervalId = setInterval(render, 10);
}
$(document).ready(init);
</script>
</head>
<body>
<canvas id="canvas" width="700" height="500"></canvas>
</body>
</html>
I can't seem to detect the errors I made. Your ideas and solutions would be greatly appreciated. :)
Your issue relates to a scope issue : you are using x,y variables through all your code, so they should be global variables. But your issues are 1) is that you didn't declare them as global variable and 2) when you initialize x,y in initBall, you declare 2 local vars that are x,y, that will hide x,y global vars.
--> add with global scope :
var x,y ;
(by the way declare also
var horizontalvelocity = 2;
var verticalvelocity = 0;
)
--> remove the var declaration in
function initBall() {
// initialise position and velocity of ball
x = 50;
y = 50;
horizontalvelocity = 2;
verticalvelocity = 0;
}
Related
hi im a newbie and im currently trying to build an app called sink ships.
I already drew the the circles with a css property and the tanks which look like this <------00000 are also moving with a with javascript I used for that the window.addEventlistener and giving each movement a property case going left right up down. Now I want the circle which symbolices the tanks to move down and up and up again and disappearing when I the bazooka touched the circle (tank) my code looking like this:
let circle = document.getElementById(".circle");
let moveBy = 10;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
window.addEventListener("load", () => {
circle.style.position = "absolute";
circle.style.left = 0;
circle.style.top = 0;
});
window.addEventListener("keyup", (e) => {
switch (e.key) {
case "ArrowLeft":
circle.style.left = parseInt(circle.style.left) - moveBy + "px";
break;
case "ArrowRight":
circle.style.left = parseInt(circle.style.left) + moveBy + "px";
break;
case "ArrowUp":
circle.style.top = parseInt(circle.style.top) - moveBy + "px";
break;
case "ArrowDown":
circle.style.top = parseInt(circle.style.top) + moveBy + "px";
break;
}
});
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
x += dx;
y += dy;
}
setInterval(draw, 10);
.circle {
height: 100px;
width: 100px;
border-radius: 50%;
background-color: rgb(0, 0, 0);
text-align-last: grid;
justify-content: center;
align-items: center;
ast: right;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body style="background-color: rgb(177, 133, 133)">
<canvas id="myCanvas"></canvas>
<div id=".circle"><------000</div>
<div class="circle"></div>
</body>
</html>
Now my question could someone help me with a code that could make my circle move up and down I already copied a code from the internet maybe it could help with the first steps
The question is a little vague to me. I interpret it to mean that you want the large black circle to move up and down, the ASCII art to move with the keyboard, and if the front of the ASCII art touches the big circle, the big circle disappears.
Traditionally, one would write a game for the browser using a canvas object. In your code you have some content that is trying to use a canvas, but since you do not declare a canvas or create a canvas element in javascript, the canvas code is throwing exceptions. My recommendation would be stop using html elements and move to a canvas. However, to keep the answer as close to the origin code as possible, I'll provide some code that uses the original HTML elements followed by a canvas implementation.
Element-base solution
If you want to build the game using just html elements, you would need to make the following changes to your script:
// var canvas = document.getElementById("myCanvas");
// var ctx = canvas.getContext("2d");
// var x = canvas.width/2;
// var y = canvas.height-30;
let x = 100;
let y = 100;
let ticks = 0;
var dx = 2;
var dy = 100;
let bigCircle = document.getElementsByClassName('circle')[0];
// ctx.beginPath();
function drawBall() {
// ctx.arc(x, y, 10, 0, Math.PI*2);
// ctx.fillStyle = "#0095DD";
// ctx.fill();
// ctx.closePath();
}
function styleStringToNumber(string) {
return +(string.substring(0, string.length - 2));
}
function draw() {
//ctx.clearRect(0, 0, canvas.width, canvas.height);
// drawBall();
ticks++;
animatedY = Math.cos(ticks / 100) * 100 + dy;
bigCircle.style.top = animatedY;
let circleBoundary = document.getElementById(".circle").getBoundingClientRect();
let tip = { x: circleBoundary.left, y: (circleBoundary.top + circleBoundary.bottom) / 2 }
let distance = Math.sqrt((styleStringToNumber(bigCircle.style.top) + 50 - tip.y) ** 2 + (styleStringToNumber(bigCircle.style.left) + 50 - tip.x) ** 2)
if (distance < 50)
bigCircle.style.visibility = "hidden"
}
setInterval(draw, 10);
You also have some ill-formatted code in you css. You can resolve the issues to removing the end of the last line so it only reads "align-items: center;" and by appending a final closing curly brace.
Description
Lines that have to do with a canvas have been commented out
We get a reference to the big circle by querying for a list of elements with the class circle and grabbing the first one in the list.
We add a function "styleStringToNumber" that will take the positional data from the big circle's style and convert it from a string with a trailing "px" to a number.
Move the big circle up and down with time. There are many ways to do this. I chose to use a simple trigonometric function since it eases in and out of it's vertical movement.
Get the boundary of the element referenced by circle
Use the Pythagorean theorem to find the distance from the center of the big circle and the left side of the 'circle' bounding box.
If the distance is less than the radius of the big circle, then change the visibility to hidden.
Using a Canvas
If you were to convert to using a canvas, you could reproduce this behavior this:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
html,
body {
overflow: hidden
}
</style>
</head>
<body onkeyup='keyup(event)'>
<canvas id="canv" width=640 height=480></canvas>
<script>
let ctx = document.querySelector("#canv").getContext("2d")
let asciiPosition = { x: 0, y: 10 }
let circlePosition = { x: 0, y: 0 }
let ticks = 0;
let showBigCircle = true;
function main() {
//update and draw every 10ms
setInterval(update, 10)
}
//Change the state of the game
function update() {
ticks++
circlePosition.y = Math.cos(ticks / 100) * 100 + 100;
//Check if they are in collision
let distance = Math.sqrt((asciiPosition.x - (circlePosition.x + 50))**2 + (asciiPosition.y - (circlePosition.y + 50))**2)
if(distance < 50)
showBigCircle = false;
draw();
}
//Draw the game
function draw() {
ctx.fillStyle = "lightgreen";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillStyle = "black"
ctx.fillText("<------000", asciiPosition.x, asciiPosition.y)
if (showBigCircle) {
ctx.beginPath();
ctx.arc(circlePosition.x + 50, circlePosition.y + 50, 50, 0, Math.PI * 2);
ctx.fill();
}
}
//Respondto keyboard events
function keyup(e) {
let jump = 10;
switch (e.key) {
case 'ArrowLeft':
asciiPosition.x -= jump;
break;
case 'ArrowRight':
asciiPosition.x += jump;
break;
case 'ArrowUp':
asciiPosition.y -= jump;
break;
case 'ArrowDown':
asciiPosition.y += jump;
break;
}
}
//Start the game loop
main();
</script>
</body>
</html>
I've taken nearly every possible countermeasure to prevent my program from drawing two dots instead of one on my chart. I want the dot in the middle to be shown, not the one in the top left. It seems to me the dot is being drawn once in the top left, matching the coordinates and everything, but then it draws a second dot with the translate method. Of course this is just speculation from what's happening on screen. The problem is occurring somewhere in the draw() function, init() function, or the anim() function - I can't pinpoint where the problem is.
let graph = document.getElementById('chart');
let c = graph.getContext('2d');
graph.height = 754;
graph.width = 754;
function algebra() {
xVertex = 2 * 10;
yVertex = 5 * 10;
let radius = 3;
let node = [];
function Node(xVertex, yVertex, radius) {
this.r = radius;
this.xV = xVertex;
this.yV = yVertex;
this.draw = function() {
c.beginPath();
c.arc(this.xV, this.yV, this.r, 0, Math.PI * 2, false);
c.fillStyle = "red";
c.fill();
c.translate(377, 377);
c.stroke();
c.closePath();
};
this.update = function() {
this.draw();
};
};
function init() {
node.push(new Node(xVertex, yVertex, radius));
anim();
};
function anim() {
requestAnimationFrame(anim);
for (let i = 0; i < node.length; i++) {
node[i].update(node);
};
c.clearRect(0, 0, graph.width, graph.height);
console.log(node);
};
init();
};
#graph {
left: 100px;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Proof of concept </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="graph">
<canvas id="chart"></canvas>
<div id="y-axis"></div>
<div id="x-axis"></div>
</div>
<div id="button" onclick="algebra()">
<div id="btext">Calculate</div>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
I think I found your errors:
1) When you call anim() it must first clear the canvas and then redraw all points.
2) Call the next animation frame after all points are drawn on the canvas
And the main problem:
3) You are doing a translate of the canvas origin on each point drawn (and a large one (377, 377)). Since the origin is changing at every iteration or point drawn also the canvas section that is being erased is moving. The two points you got were the first and second iterarions, the others were offscreen.
What you need to do is translate the canvas origin to its middle only once, just after:
let c = graph.getContext('2d');
graph.height = 754;
graph.width = 754;
//Translate the origin to the canvas' center (do this only once)
c.translate(graph.width/2, graph.height/2);
If the canvas origin has moved to the center, then you must also erase the canvas from -width/2 to width/2 and height/2 to height/2. To do this you must use:
c.clearRect(-graph.width/2, -graph.height/2, graph.width, graph.height);
Just for fun, I've added three more points to the node array and adding a random number between -1 and 1 to each coordinate in every iteration. This results in a Brownian like motion simulation.
let graph = document.getElementById('chart');
let c = graph.getContext('2d');
graph.height = 754;
graph.width = 754;
//Translate the origin to the canvas' center (do this only once)
c.translate(graph.width/2, graph.height/2);
function algebra() {
//Changed to 0 to plot at center
xVertex = 0;
yVertex = 0;
let radius = 3;
let node = [];
function Node(xVertex, yVertex, radius) {
this.r = radius;
this.xV = xVertex;
this.yV = yVertex;
this.draw = function() {
c.beginPath();
c.arc(this.xV, this.yV, this.r, 0, Math.PI * 2, false);
c.fillStyle = "red";
c.fill();
c.stroke();
c.closePath();
};
this.update = function() {
//this will generate random movement in x and y.
this.xV += Math.random()*2-1;
this.yV += Math.random()*2-1;
this.draw();
};
};
function init() {
node.push(new Node(xVertex, yVertex, radius));
node.push(new Node(xVertex, yVertex, radius));
node.push(new Node(xVertex, yVertex, radius));
node.push(new Node(xVertex, yVertex, radius));
anim();
};
function anim() {
//First clear the canvas then redraw
c.clearRect(-graph.width/2, -graph.height/2, graph.width, graph.height);
for (let i = 0; i < node.length; i++) {
node[i].update(node);
};
//After all are drawn, call the next Animation Frame
requestAnimationFrame(anim);
};
init();
};
#graph {
left: 100px;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Proof of concept </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="graph">
<canvas id="chart"></canvas>
<div id="y-axis"></div>
<div id="x-axis"></div>
</div>
<div id="button" onclick="algebra()">
<div id="btext">Calculate</div>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
i want the bullet coming from the red square to hit the blue square wherever it is , but it doesn't go towards the blue square , what should i do ?
i tried Math.atan2(100, 100)/ Math.PI * 180;and the result is 45° wich is correct , but it shoots in the opposite direction rather than towards the blue square ,
im confused please help , sorry for any mistake
thank you
<!DOCTYPE html>
<head>
<meta charset="UTF-8"/>
<title> just my game </title>
</head>
<body>
<canvas id="canvas" width="1000" height="1000"></canvas>
<script>
/* LEGEND
red : red square
blue : blue square
Dim : width or hight (px) (dimention)
posX : position on the X axis
posY : position on the Y axis
Inc : increment (known as speed)
aimAng : aiming angle
*/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var redDim = 20;
var redPosX = 200;
var redPosY = 200;
var redPosXInc = 1;
var redPosYInc = 1;
var blueDim = 15;
var bluePosX = 300;
var bluePosY = 300;
var bulletDim = 6;
var bulletPosX = bluePosX ;
var bulletPosY = bluePosY ;
var bulletPosXInc;
var bulletPosYInc;
var aimAng;
var bullet = false;
//filling the canvas
animate();
function animate () {
setInterval(print, 25);
}
function print () {
//clearing the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
//printing the canvas
context.fillStyle="#c1d9ff";
context.fillRect(0, 0, canvas.width, canvas.height);
//printing red square
context.fillStyle="red";
context.fillRect(redPosX, redPosY, redDim, redDim);
//printing blue square
context.fillStyle="blue";
context.fillRect(bluePosX, bluePosY, blueDim, blueDim);
//calculating the aiming angle between the two squares
aimAng = Math.atan2(redPosY - bluePosY, redPosX - bluePosX) / Math.PI * 180;
//calculating the increment of the position of the bullet (if the bullet is not active)
if (bullet == false) {
bulletPosXInc = Math.cos(aimAng)*5;
bulletPosYInc = Math.sin(aimAng)*5;
bullet = true;
}
//printing the bullet
context.fillStyle="black";
context.fillRect(bulletPosX, bulletPosY, bulletDim, bulletDim);
//changing position of the bullet for the next print
bulletPosX = bulletPosX + bulletPosXInc;
bulletPosY = bulletPosY + bulletPosYInc;
}
</script>
</body>
Math.sin and Math.cos take radians so you do not need to convert the result into degrees! So ignore the * 180 / PI bit
For a smoother and more efficient way for animating, try calling the animation frame when the system is ready to paint the frame. use
window.requestAnimationFrame(print);
Full code:
<head>
<meta charset="UTF-8"/>
<title> just my game </title>
</head>
<body>
<canvas id="canvas" width="1000" height="1000"></canvas>
<script>
/* LEGEND
red : red square
blue : blue square
Dim : width or hight (px) (dimention)
posX : position on the X axis
posY : position on the Y axis
Inc : increment (known as speed)
aimAng : aiming angle
*/
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var redDim = 20;
var redPosX = 200;
var redPosY = 200;
var redPosXInc = 1;
var redPosYInc = 1;
var blueDim = 15;
var bluePosX = 300;
var bluePosY = 300;
var bulletDim = 6;
var bulletPosX = bluePosX ;
var bulletPosY = bluePosY ;
var bulletPosXInc;
var bulletPosYInc;
var aimAng;
var bullet = false;
var speed = 6;
//filling the canvas
animate();
function animate () {
window.requestAnimationFrame(print);
}
function print () {
//clearing the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
//printing the canvas
context.fillStyle="#c1d9ff";
context.fillRect(0, 0, canvas.width, canvas.height);
//printing red square
context.fillStyle="red";
context.fillRect(redPosX, redPosY, redDim, redDim);
//printing blue square
context.fillStyle="blue";
context.fillRect(bluePosX, bluePosY, blueDim, blueDim);
//calculating the aiming angle between the two squares in radians
aimAng = Math.atan2(redPosY - bluePosY, redPosX - bluePosX) ;
//calculating the increment of the position of the bullet (if the bullet is not active)
if (bullet == false) {
bulletPosXInc = Math.cos(aimAng)*speed ;
bulletPosYInc = Math.sin(aimAng)*speed ;
bullet = true;
}
//printing the bullet
context.fillStyle="black";
context.fillRect(bulletPosX, bulletPosY, bulletDim, bulletDim);
//changing position of the bullet for the next print
bulletPosX = bulletPosX + bulletPosXInc;
bulletPosY = bulletPosY + bulletPosYInc;
window.requestAnimationFrame(print);
}
</script>
</body>
I've read many posts and gone through several tutorials on HTML5 and the canvas specifically, but so far I have been unable to replicate my exact problem. If there is an answer for it already out there, please point me in the right direction.
My ultimate goal is to make a simple Pong game. I've drawn the basic objects using JavaScript and now I am trying to get the player (left) paddle to move. The problem I am running into with my current code is that instead of moving the paddle, it fills in the area it travels to. Through various trials and error of adapting and trying different methods I don't think the paddle is being elongated (adding pixels to the height), but it seems like a new paddle object is being created rather than the one being moved.
I've looked it over and over again (you guys aren't a first-ditch effort), but can't seem to figure out what's happening. Any help would be much appreciated.
// Requests a callback 60 times per second from browser
var animate = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { window.setTimeout(callback, 1000/60) };
// Get canvas and set context
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "white";
// Settle variables for canvas width and height
var canvas_width = 500;
var canvas_height = 400;
// Set varaibles for paddle width and height
var paddle_width = 15;
var paddle_height = 75;
// Initializes variables
var playerScore = 0;
var computerScore = 0;
var player = new Player();
var computer = new Computer();
var ball = new Ball((canvas_width/2),(canvas_height/2));
// Renders the pong table
var render = function() {
player.render();
computer.render();
ball.render();
};
var update = function() {
player.update();
};
// Callback for animate function
var step = function() {
update();
render();
animate(step);
};
// Creates paddle object to build player and computer objects
function Paddle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.x_speed = 0;
this.y_speed = 0;
};
function Player() {
this.paddle = new Paddle(1, ((canvas_height/2) - (paddle_height/2)), paddle_width, paddle_height);
};
function Computer() {
this.paddle = new Paddle((canvas_width - paddle_width - 1), ((canvas_height/2) - (paddle_height/2)), paddle_width, paddle_height);
};
// Creates ball object
function Ball(x, y) {
this.x = x;
this.y = y;
this.radius = 10;
};
// Adds render functions to objects allowing them to be drawn on canvas
Ball.prototype.render = function() {
context.beginPath();
context.arc(this.x, this.y, this.radius, Math.PI * 2, false);
context.fillStyle = "white";
context.fill();
context.closePath();
};
Paddle.prototype.render = function() {
context.fillStyle = "white";
context.fillRect(this.x, this.y, this.width, this.height);
};
Player.prototype.render = function() {
this.paddle.render();
};
// Appends a move method to Paddle prototype
Paddle.prototype.move = function(x, y) {
this.y += y;
this.y_speed = y;
};
// Updates the location of the player paddle
Player.prototype.update = function() {
for(var key in keysDown) {
var value = Number(key);
if(value == 38) {
this.paddle.move(0, -4);
} else if (value == 40) {
this.paddle.move(0, 4);
} else {
this.paddle.move(0, 0);
}
}
};
Computer.prototype.render = function() {
this.paddle.render();
};
// Draws center diving line
context.strokeStyle = "white";
context.setLineDash([5, 3]);
context.beginPath();
context.moveTo((canvas_width/2), 0);
context.lineTo((canvas_width/2), canvas_height);
context.stroke();
context.closePath();
// Draws score on canvas
context.font = "40px Arial";
context.fillText('0', (canvas_width * .23), 50);
context.fillText('0', (canvas_width * .73), 50);
window.onload = function() {
animate(step);
};
var keysDown = {};
window.addEventListener("keydown", function(event) {
keysDown[event.keyCode] = true;
});
window.addEventListener("keyup", function(event) {
delete keysDown[event.keyCode];
});
My apologies: I cut the html/css code and meant to paste it, but forgot.
pong.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pong</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="500" height="400"></canvas>
<script src="main.js"></script>
</body>
</html>
style.css:
#canvas {
background-color: black;
}
The canvas itself has no "objects", it's just a bitmap, and anything you draw on it just changes the colours of certain pixels, making it look like it's drawing "on top" of what's already there but it doesn't even do that. It just flips pixel colours.
I don't see any code that "resets" the canvas for your next frames, so you're literally just drawing the same paddle at a different height value by colouring different pixels with the paddle's colours without recolouring the original pixels using the background colour.
The easiest solution here is to add a context.clearRect(0, 0, canvas.width, canvas.height); at the start of render():
var render = function() {
// clear the canvas so we can draw a new frame
context.clearRect(0,0,canvas.width,canvas.height);
// draw the frame content to the bitmap
player.render();
computer.render();
ball.render();
};
Note that this reveals you also need to draw your scores and center line every frame. Either that, or you need to make sure your paddles (and your ball) first restore the background colour on their old position, before drawing themselves on their new position, which would require considerably more code.
I am trying to create a blackhole simulation that will display a blackhole and 100 circles travelling away from it at a speed that would be decreasing because of gravity. Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>test trou noir</title>
<script>
var canvas = document.getElementById ("space");
var ctx = canvas.getContext ('2d');
var blackhole;
var circle = new Array();
window.onload = init;
function init (){
var G = 6.67e-11, //gravitational constant
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3;// scaled radius
blackhole = new Ball (pixel_Rs, 700, 400, "black");
blackhole.draw ();
};
function Ball (radius, posX, posY, color){
this.radius = radius;
this.posX = posX;
this.posY = posY;
this.color = color;
}
Ball.prototype.draw = function (ctx){
var ctx = canvas.getContext ('2d');
ctx.fillStyle = this.color;
ctx.beginPath ();
ctx.arc (this.posX, this.posY, this.radius, 0, 2*Math.PI);
ctx.closePath ();
ctx.fill();
};
</script>
<style>
body {
background-color:#021c36 ;
margin: 0px;}
</style>
</head>
<body>
<canvas id ="space", width = "1400", height = "800">
</canvas>
</body>
</html>
Can someone tell me why I can't make the canvas draw the blackhole and how to create those 100 circles and animate them, I have literally tried everything and I can't make it work
Thanks a lot
You're missing the canvas from your html:
<canvas id="space"/>
You need to pass ctx to your draw function:
blackhole.draw(ctx);
Though it still doesn't draw, but that might be because of the sizes/colors.
update:
Here's a version that you can see: https://jsfiddle.net/gjwh33mq/2/ From here you can gradually change the numbers. (There's some strange bug, the window.onload is not getting called, so I added a call at the end of the js)