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)
Related
I'm trying to get the area of a polygone draw onclick in a canvas element
In the image above I try to get the area inside the red point which has a some opacity.
Is there anyway to do that "on the fly" which mean for each polygon draw.
I've already seen earcut.js which allow triangulation but I don't really understand how to get area whith this
var canvas = $('canvas');
var context = canvas[0].getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
$(canvas).attr({
width : this.width,
height: this.height
});
context.drawImage(imageObj,0,0);
};
imageObj.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
var clicks = [];
function drawPolygon(){
context.fillStyle = 'rgba(100,100,100,0.5)';
context.strokeStyle = "#df4b26";
context.lineWidth = 1;
context.beginPath();
context.moveTo(clicks[0].x, clicks[0].y);
for(var i=1; i < clicks.length; i++) {
context.lineTo(clicks[i].x,clicks[i].y);
}
context.closePath();
context.fill();
context.stroke();
};
function drawPoints(){
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clicks.length; i++){
context.beginPath();
context.arc(clicks[i].x, clicks[i].y, 3, 0, 2 * Math.PI, false);
context.fillStyle = '#ffffff';
context.fill();
context.lineWidth = 5;
context.stroke();
}
};
function redraw(){
canvas.width = canvas.width; // Clears the canvas
context.drawImage(imageObj,0,0);
drawPolygon();
drawPoints();
};
canvas
.mouseup(function (e) {
clicks.push({
x: e.offsetX,
y: e.offsetY
});
redraw();
});
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>draw polygon with canvas</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas width="600" height="400"></canvas>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
There is very simple algorithm to calculate area of polygon with given vertex coordinates: Shoelace formula
A = 1/2* Sum((x[i+1] + x[i]) * ([y[i+1] - y[i]))
(note indexes wrap in circular manner, so x[n]=x[0])
that might be implemented in a single loop.
I have some HTML and Javascript code that draws a 2D canvas in the page. In the task manager, I can see memory increasing rapidly until the web page freezes.
Please let me know how I can prevent memory leaks or provide me with some alternative code that is able to draw canvas on the browser without creating such leaks.
function setup() {
// insert setup code here
}
function draw() {
// insert drawing code here
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 600;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";
document.body.appendChild(canvas);
var c2 = canvas.getContext('2d');
var centerX=canvas.width/2-100;
var centerY=canvas.height/2-100;
c2.fillStyle = '#696969';
c2.beginPath();
c2.moveTo(centerX, centerY);
c2.lineTo(centerX+200,centerY);
c2.lineTo(centerX+200, centerY+200);
c2.lineTo(centerX, centerY+200);
c2.closePath();
c2.fill();
// adding source location
var ctx = canvas.getContext("2d");
ctx.fillStyle = '#008000';
ctx.beginPath();
ctx.arc( 20, canvas.height-20, 10, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();
ctx.fill();
// adding destination location
var ctx1 = canvas.getContext("2d");
ctx1.fillStyle = '#f00';
ctx1.beginPath();
ctx1.arc( canvas.width-20, 20, 10, 0, 2 * Math.PI);
ctx1.stroke();
ctx1.closePath();
ctx1.fill();
}
<!DOCTYPE html>
<html>
<head>
<title>Robot Path Planning</title>
<style>
body {
padding: 0;
margin: 0;
}
</style>
<script src="../p5.min.js"></script>
<script src="../addons/p5.dom.min.js"></script>
<script src="../addons/p5.sound.min.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>
Browser
Memory consumption
Apparently your code is creating a new canvas entity for each draw call and this doesn't make sense.
You should instead create the canvas only once and then just do drawing on it in the draw call. If you need to clear the previous frame you can just reset the width/height properties or call clearRect.
Hello I wanted to know if anyone can provide tips or direction on an issue i'm having with a triangle animation. I have a partial animation that is not continuous, it jitters at the end of the animation. I'm looking for advise how to make a full rotation. If anyone can also assist in how to add multiple rotations that would be amazing.
Thank you ..
<!DOCTYPE html>
<html>
<head>
<title>Triangle Animation Team B</title>
</head>
<body>
<canvas id="canvas" width="900" height="600"></canvas>
<script>
function makeTriangle(x1,y1,x2,y2,x3,y3) {
var canvas = document.getElementById('canvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
var Array = ['red','green', 'black'];
var color = Array[Math.floor(Math.random() * 3)];
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.lineTo(x3,y3);
ctx.lineTo(x1,y1);
ctx.fillStyle = color;
ctx.fill();
}
}
makeTriangle('400','38','465','76','200','400');
var x = 200;
window.setInterval( function() {
var context = document.getElementById('canvas').getContext('2d');
context.clearRect(0, 0, 1000, 500, 0);
x++;
if (x > 500) x = 300;
makeTriangle('400','38',x,'76','400','200');
}, 20);
</script>
</body>
</html>
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;
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>Clock</title>
</head>
<body>
<canvas id="canvas" width="500" height="500">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<script type='text/javascript' src='Clock.js'></script>
</body>
</html>
JavaScript
var canvas = document.getElementById("canvas"),
c = canvas.getContext("2d"),
Margin = 35,
NumbersRadius = canvas.width/2 - Margin,
ClockRadius = NumbersRadius - 30;
//draw the circle that bound the clock
function drawCircle() {
c.arc(canvas.width/2, canvas.height/2, ClockRadius, 0, 2*Math.PI);
c.stroke();}
//draw the numbers, which lie on the circle with radius: NumbersRadius
function drawNumbers(){
c.font = "25px Verdana";
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12],
angle;
numbers.forEach(function(numbers){
angle = Math.PI/6 * (numbers - 3);
c.fillText(numbers, canvas.width/2 + Math.cos(angle)*NumbersRadius, canvas.height/2 + Math.sin(angle)*NumbersRadius)
});}
//draw the hands
//length of each hand
var SecondHand = ClockRadius - 0.25*ClockRadius,
MinuteHand = SecondHand-0.25*SecondHand,
HourHand = MinuteHand-0.25*MinuteHand;
//Assume that we start at 3:00. i is the number of seconds
function drawHands() {
var i = 0,
angle = -1/30*Math.PI*i;
//draw the SecondHand
c.moveTo(canvas.width/2, canvas.height/2);
c.lineTo(canvas.width/2 + Math.cos(angle)*ClockRadius, canvas.height/2 + Math.sin(angle)*ClockRadius);
c.stroke();
//draw the MinuteHand
c.moveTo(canvas.width/2, canvas.height/2);
c.lineTo(canvas.width/2 + Math.cos(-1/60*angle)*ClockRadius, canvas.height/2 + Math.sin(-1/60*angle)*ClockRadius);
c.stroke;
//draw the HourHand
c.moveTo(canvas.width/2, canvas.height/2);
c.lineTo(canvas.width/2 + Math.cos(-1/Math.pow(60,2)*angle)*ClockRadius, canvas.height/2 + Math.sin(-1/Math.pow(60,2)*angle*ClockRadius));
c.stroke();
i++;
}
function drawClock() {
c.clearRect(0,0,canvas.width,canvas.height);
drawCircle();
drawNumbers();
drawHands();
}
loop = setInterval(drawClock, 1000);
I don't know why my clock is not running. All the hands point and stay still at 3:00. The NumbersRadius is the radius of the circle that the coordinate of the numbers are on. The ClockRadius, which is smaller than NumbersRadius, is the radius of the circle that bound the hands.
In drawHands, you're resetting i to 0 every time. Move var i = 0 outside that function.
var i = 0;
function drawHands() {
var angle = -1/30*Math.PI*i;
//draw the SecondHand
c.moveTo(canvas.width/2, canvas.height/2);
...
http://jsfiddle.net/trevordixon/bW73Y/