Moving an Object according to mouse coordinates - javascript

How do I get the following script to work? I wanted to be able to move the ship to the mouse coordinates. The space itself should move and the ship should stay in the centerview.
Would be great if you can modify the script as everybody writes his functions different.
Finally if the button is clicked I want the ship to move to that destination
I tried it when it worked and the ship never moved and I don't know if it has to do with the prototype.update function or not.
Is prototype.update or .render the same as if I would write this.update or this.render?
<script>
function domanDown(evt)
{
switch (evt)
{
case 38: /* Up arrow was pressed or button pressed*/
offsetY+=100 ;
break;
case 40: /* Down arrow was pressed or button pressed*/
offsetY-=100;
break;
case 37: /* Left arrow was pressedor button pressed*/
offsetX+=100;
break;
case 39: /* Right arrow was pressed or button pressed*/
offsetX-=100;
break;
}
}
window.requestAnimationFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f,1e3/60);
}
}();
var Obj = function (x,y,sp,size){
this.size = size;
this.x = x;
this.y = y;
this.color = sp;
this.selected = 0;
}
var Planet_Class = function (x,y,sp){
this.type = 'Planet_Class';
this.depot = 11;
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Planet_Class.prototype.update =function () {
}
Planet_Class.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var Usership = function(x,y,sp){
this.depot = 10;
this.type = 'Usership';
this.xtype = new Obj(x,y,sp,10);
w.objects.push(this);
Usership.prototype.update =function (x,y) {
this.xtype.x = x || 20;
this.xtype.y = y || 20;
}
Usership.prototype.render =function () {
ctx.save();
ctx.beginPath();
ctx.fillStyle = this.xtype.color;
ctx.fillRect(this.xtype.x, this.xtype.y,this.xtype.size,this.xtype.size);
ctx.fill();
ctx.restore();
}
}
var World = function(){
this.objects = new Array();
this.count = function(type,sp){
var cnt = 0;
for(var k = 0;k<this.objects.length;k++)
cnt++;
return cnt;
}
}
renderWorld = function(){
requestAnimationFrame(renderWorld);
var spliceArray = Array();
ctx.beginPath();
objcnt = w.objects.length;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "white";
ctx.fill();
i = 0;
while(i < objcnt){
w.objects[i].update();
w.objects[i].render();
if(w.objects[i].depot < 1)
spliceArray.push(i);
i++;
}
for(var k = 0;k<spliceArray.length;k++)
{
w.objects.splice(spliceArray[k],1); }
}
function r1(max,min){
return (Math.floor(Math.random() * (max - min)) + 1);
}
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d"),
width = 1024,
height = 768;
offsetX = (canvas.width/2)-300; /Startpoint x for the Ship
offsetY = (canvas.height/2)-300; /Startpoint y for the Ship
generateshipx = -offsetX + (canvas.width/2);
generateshipy = -offsetY + (canvas.height/2);
mX = generateshipx;
mY = generateshipy;
w = new World();
new Usership(generateshipx,generateshipy,'green');
for(i=1;i<4;i++){
new Planet_Class(r1(600,2),r1(600,2),'red');
}
canvas.addEventListener("click", function (e) {
mX = e.pageX- canvas.offsetLeft -offsetX) ;
mY = e.pageY - canvas.offsetTop -offsetY) ;
});
renderWorld();
</script>
<html>
<head>
</head>
<body style="background-color:black;">
<canvas style="z-index:1" width="1024" height="768" id="canvas"></canvas>
<input type="button" style="z-index:2; position:absolute; top:300; left:10" value="uo" onCLick="domanDown(38)()">
<input type="button" style="z-index:2; position:absolute; top:340; left:10" value="down" onCLick="domanDown(40)">
<input type="button" style="z-index:2; position:absolute; top:380; left:10" value="left" onCLick="domanDown(37)">
<input type="button" style="z-index:2; position:absolute; top:420; left:10" value="right" onCLick="domanDown(39)">
<input type="button" style="z-index:2; position:absolute; top:460; left:10" value="move" onCLick="moveObj()">
</body>
</html>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
cursor: crosshair;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var ctx = null;
var bounds = null;
var isRotating = false;
var isMoving = false;
var pan = {
x: 0.0,
y: 0.0
};
var target = {
x: 0.0,
y: 0.0,
dist: 0.0
};
var ship = {
x: (canvasWidth * 0.5)|0,
y: (canvasHeight * 0.5)|0,
width: 10.0,
height: 10.0,
rotation: 0.0,
deltaRotation: 0.0
};
var stars = [];
stars.length = 100;
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx = canvas.getContext("2d");
bounds = canvas.getBoundingClientRect();
for (var i = 0; i < stars.length; ++i) {
stars[i] = {
x: (Math.random() * 4 * canvasWidth - 2 * canvasWidth)|0,
y: (Math.random() * 4 * canvasHeight - 2 * canvasHeight)|0
};
}
loop();
}
window.onmousedown = function(e) {
isRotating = true;
isMoving = false;
target.x = pan.x + e.clientX - bounds.left;
target.y = pan.y + e.clientY - bounds.top;
}
function loop() {
// Tick
// Rotate to face target
if (isRotating) {
// Vector creation
var tX = ship.x - target.x;
var tY = ship.y - target.y;
var tL = Math.sqrt(tX**2 + tY**2);
var fX = Math.sin(ship.rotation);
var fY = -Math.cos(ship.rotation);
var sX = Math.sin(ship.rotation + Math.PI * 0.5);
var sY = -Math.cos(ship.rotation + Math.PI * 0.5);
// Normalization
tX = tX / tL;
tY = tY / tL;
// Left or right?
var a = 1.0 - Math.abs(tX * fX + tY * fY);
ship.rotation += 0.075 * (sX * tX + sY * tY < 0.0 ? 1.0 : -1.0);
if (a < 0.01) {
target.dist = tL;
isRotating = false;
isMoving = true;
}
}
// Accelerate to target
if (isMoving) {
ship.x += Math.sin(ship.rotation) * 1.0;
ship.y -= Math.cos(ship.rotation) * 1.0;
if (--target.dist < 0.0) {
isMoving = false;
}
}
// Render
// Update pan coordinates
pan.x = ship.x - canvasWidth * 0.5;
pan.y = ship.y - canvasHeight * 0.5;
// Draw background
ctx.fillStyle = "#222222";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
ctx.fillStyle = "white";
for (var i = 0; i < stars.length; ++i) {
ctx.fillRect(
stars[i].x - pan.x,
stars[i].y - pan.y,
2,
2
);
}
// Draw ship
ctx.strokeStyle = "white";
ctx.fillStyle = "darkred";
ctx.translate(canvasWidth * 0.5,canvasHeight * 0.5);
ctx.rotate(ship.rotation);
ctx.beginPath();
ctx.moveTo(-ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(ship.width * 0.5,ship.height * 0.5);
ctx.lineTo(0.0,-ship.height * 0.5);
ctx.lineTo(-ship.width * 0.5,ship.height * 0.5);
ctx.fill();
ctx.stroke();
ctx.rotate(-ship.rotation);
ctx.translate(-canvasWidth * 0.5,-canvasHeight * 0.5);
requestAnimationFrame(loop);
}
</script>
</body>
</html>

Related

How to make bullet launcher point in mouse position? Canvas JavaScript

When the mouse moves it doesn't point in the mouseX or mouseY direction.
The current method points and rotates at the top right point slightly offset on the canvas.
All the other SO questions didn't work for this specific game.
I would prefer the most straightforward answer and an explanation of how it works.
I need a vanilla javascript answer.
/**
* #type { HTMLCanvasElement }
*/
var scene = document.getElementById("scene");
var ctx = scene.getContext("2d");
var mouseX = 0;
var mouseY = 0;
var prevSceneTranslateXL = 0;
var prevSceneTranslateYL = 0;
var prevSceneTranslateXR = 0;
var prevSceneTranslateYR = 0;
var sceneTranslateX = 0;
var sceneTranslateY = 0;
var friction = 4 / 5;
var keysDown = [];
scene.width = window.innerWidth;
scene.height = window.innerHeight;
var bg = new Image();
bg.src = "./assets/groundBgAlt.png";
class Player {
constructor(x, y, radius, color, borderColor) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.borderColor = borderColor;
this.velX = 0;
this.velY = 0;
this.speed = 15;
this.angle = 0;
}
}
class Enemy {
constructor(radius, color, borderColor) {
this.x = Math.random() * scene.width + 25;
this.y = Math.random() * scene.height + 25;
this.radius = radius;
this.color = color;
this.borderColor = borderColor;
this.velX = 0;
this.velY = 0;
this.speed = 15;
this.angle = 0;
}
}
var player1 = new Player(1000, 1000, 25, "#0080ff", "#606060");
var enemies = [];
// for (i = 0; i < 20; i++) {
// enemies.push(new Enemy(50, 50, "#ff0000", "#bb0000"));
// }
function drawPlayer(player) {
ctx.strokeStyle = "#606060";
ctx.lineWidth = 2;
ctx.fillStyle = "#cccccc";
ctx.save();
ctx.beginPath();
ctx.translate(player.x, player.y);
ctx.rotate(player1.angle);
ctx.roundRect(-10, -45, 20, 25, 2);
ctx.fill();
ctx.stroke();
ctx.closePath();
ctx.restore();
ctx.strokeStyle = player.borderColor;
ctx.lineWidth = 2;
ctx.fillStyle = player.color;
ctx.beginPath();
ctx.arc(player.x, player.y, player.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
function drawEnemies(enemy) {
ctx.strokeStyle = enemy.borderColor;
ctx.lineWidth = 3;
ctx.fillStyle = enemy.color;
ctx.beginPath();
ctx.rect(enemy.x, enemy.y, enemy.width, enemy.height);
ctx.fill();
ctx.stroke();
ctx.closePath();
}
var gradientBG = ctx.createRadialGradient(1000, 1000, 1000, 1000, 1000, 100);
gradientBG.addColorStop(0.0, "#ffffff");
gradientBG.addColorStop(1.0, "#eeeeee");
function main() {
ctx.clearRect(-250, -250, 2500, 2500);
ctx.fillStyle = gradientBG;
ctx.fillRect(0, 0, 2000, 2000);
if (player1.x < 0) {
sceneTranslateX = prevSceneTranslateXL;
player1.x = 0;
player1.velX = 0;
}
if (player1.x > 2000) {
sceneTranslateX = prevSceneTranslateXR;
player1.x = 2000;
player1.velX = 0;
}
if (player1.y < 0) {
sceneTranslateY = prevSceneTranslateYL;
player1.y = 0;
player1.velY = 0;
}
if (player1.y > 2000) {
sceneTranslateY = prevSceneTranslateYR;
player1.y = 2000;
player1.velY = 0;
}
if (keysDown["w"] || keysDown["ArrowUp"]) {
if (player1.velY > player1.speed * -1) {
player1.velY--;
}
}
if (keysDown["a"] || keysDown["ArrowLeft"]) {
if (player1.velX > player1.speed * -1) {
player1.velX--;
}
}
if (keysDown["s"] || keysDown["ArrowDown"]) {
if (player1.velY < player1.speed) {
player1.velY++;
}
}
if (keysDown["d"] || keysDown["ArrowRight"]) {
if (player1.velX < player1.speed) {
player1.velX++;
}
}
player1.velX *= friction;
player1.velY *= friction;
player1.x += player1.velX;
player1.y += player1.velY;
sceneTranslateX *= friction;
sceneTranslateY *= friction;
sceneTranslateX += -player1.velX;
sceneTranslateY += -player1.velY;
prevSceneTranslateXL = sceneTranslateX - 1;
prevSceneTranslateYL = sceneTranslateY - 1;
prevSceneTranslateXR = sceneTranslateX + 1;
prevSceneTranslateYR = sceneTranslateY + 1;
ctx.translate(sceneTranslateX / 5, sceneTranslateY / 5);
drawPlayer(player1);
// for (i = 0; i < enemies.length; i++) {
// drawEnemies(enemies[i]);
// }
requestAnimationFrame(main);
}
ctx.translate((scene.width / 2) - player1.x, (scene.height / 2) - player1.y);
main();
document.addEventListener("keydown", (e) => {
keysDown[e.key] = true;
});
document.addEventListener("keyup", (e) => {
keysDown[e.key] = false;
});
document.addEventListener("mousemove", (e) => {
var angle = Math.atan2(e.pageY - player1.y, e.pageX - player1.x);
player1.angle = angle;
});
* {
font-family: roboto, Arial, Helvetica, sans-serif, system-ui, system 'Courier New', Courier, monospace;
padding: 0px 0px;
margin: 0px 0px;
box-sizing: border-box;
}
body {
background: radial-gradient(circle, #bbbbbb 10%, #cccccc);
overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles/styles.css">
<script src="scripts/index.js" defer></script>
<title>Document</title>
</head>
<body>
<canvas id="scene" width="1024" height="576"></canvas>
</body>
</html>
The way the game is made makes it really hard to rotate objects.

Clickable Canvas Button with Link

I have the following canvas. I want it so that when the user clicks the canvas, I will go to google.com, and I want to keep the button element. This is my code:
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
a.style.width = '200px';
a.style.height = '50px';
area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - .05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if(this.r <= .05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0,0,w,h);
for(var i = 0; i < particles.length; i++) {
if(particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if(particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for(var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max)?max:1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
#canvas{
width: 200;
height: 50;
}
<div class="wrapper">
<a href="index.html">
<button align=center onclick="handleClick()">
<canvas width="200" height="50" id="canvas" align=center></canvas>
<span class="text">SUBMIT</span>
</button>
</a>
</div>
Although, I only see the button, and no the canvas. How can I fix this?
You got a lot of errors actually buddy (variable declaration is the biggest problem) but by following the errors will give you a way to fix it, I don't know if this is the fix you want.
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d');
a.style.width = '200px';
a.style.height = '50px';
var w, h;
var area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - 0.05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if (this.r <= 0.05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0, 0, w, h);
for (var i = 0; i < particles.length; i++) {
if (particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if (particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for (var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max) ? max : 1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
#canvas {
width: 200px;
height: 50px;
}
<div class="wrapper">
<a href="index.html">
<button align=center onclick="handleClick()">
<canvas width="200" height="50" id="canvas" align=center> </canvas>
<span class="text">SUBMIT</span>
</button>
</a>
</div>

Resizing a <canvas> Element

I have the following canvas. I'm trying to make it smaller using the width and height attributes, but it doesn't work. This is my code:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="canvas" width="200" height="50"></canvas>
<script>
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
w = a.width = window.innerWidth,
h = a.height = window.innerHeight,
area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - .05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if(this.r <= .05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0,0,w,h);
for(var i = 0; i < particles.length; i++) {
if(particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if(particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for(var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max)?max:1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
</script>
</body>
</html>
Pay more attention here:
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
w = a.width = window.innerWidth,
h = a.height = window.innerHeight,
area = w * h,
As you can see, w is the width of the window and h is the height of the window. Try to edit w and h variable with custom values and tell me if it worked ;)
EDIT:
Simply replace h and w with this in your script tag:
a.style.width = '500px'; //random value, insert custom here
a.style.height = '500px';

how can I make change the color of an object with a condition using rgba colors in canvas

I'm trying to make a blackhole simulation, and although I'm almost done, I wish to make disappear the dots that are drawn on the blackhole progressively, here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>test trou noir</title>
<script>
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var G = 6.67e-11,//gravitational constant
pixel_G = G/1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31,// masseof the blackhole in kg (60 solar masses)
pixel_M = M/1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs/1e3, // scaled radius
ccolor=128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - 700) * (pos.x - 700)) + ((pos.y - 400) * (pos.y - 400)));
if (distance > pixel_Rs && visible(circles[i])) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - 400, pos.x - 700);
var evelocity = Math.sqrt( (2*pixel_G*pixel_M)/(distance*1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
} else {
ccolor -=10;
};
}
function visible(ball) {
return ball.position.x > ball.radius && ball.position.x < canvas.width - ball.radius &&
ball.position.y > ball.radius && ball.position.y < canvas.height - ball.radius;
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
if (visible(circles[i])) {
circles[i].draw(ctx);
}
}
}
function init() {
canvas = document.getElementById("space");
ctx = canvas.getContext('2d');
blackhole = new Ball(pixel_Rs, {
x: 700,
y: 400
}, "black");
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * 1400), Math.floor(Math.random() * 800));
circle = new Ball(5, vec2D, 'rgba('+ccolor+','+ccolor+','+ccolor+',1)');
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
Ball.prototype.draw = function(ctx) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
window.onload = init;
</script>
<style>
body {
background-color: #021c36;
margin: 0px;
}
</style>
</head>
<body>
<canvas id="space" , width="1400" , height="800">
</canvas>
</body>
</html>
now as you can see, I created a variable called ccolor which is integrated in the rgba code, but I don't know why the colors don't tend to zero, so the circles that are inside the blackhole gradually disappear, if someone could lend me a hand it'd be great
In update, if any circles[i] is captured by the Blackhole you decrement its this.color. It might be easier if you change this.color to an integer that you use to create a fillStyle:
ctx.fillStyle='rgba(' + this.color + ',' + this.color + ',' + this.color + ',1)'.
Here's a quick demo:
View this demo Full Page or the black hole is off-screen
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var G = 6.67e-11, //gravitational constant
pixel_G = G / 1e-11,
c = 3e8, //speed of light (m/s)
M = 12e31, // masseof the blackhole in kg (60 solar masses)
pixel_M = M / 1e32
Rs = (2 * G * M) / 9e16, //Schwarzchild radius
pixel_Rs = Rs / 1e3, // scaled radius
ccolor = 128;
function update() {
var pos, i, distance, somethingMoved = false;
for (i = 0; i < circles.length; i++) {
pos = circles[i].position;
distance = Math.sqrt(((pos.x - 700) * (pos.x - 700)) + ((pos.y - 400) * (pos.y - 400)));
if (distance > pixel_Rs && visible(circles[i])) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - 400, pos.x - 700);
var evelocity = Math.sqrt((2 * pixel_G * pixel_M) / (distance * 1e-2));
delta.x += Math.cos(forceDirection) * evelocity;
delta.y += Math.sin(forceDirection) * evelocity;
pos.x += delta.x;
pos.y += delta.y;
somethingMoved = true;
} else {
circles[i].color -= 0.50;
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function visible(ball) {
return ball.position.x > ball.radius && ball.position.x < canvas.width - ball.radius &&
ball.position.y > ball.radius && ball.position.y < canvas.height - ball.radius;
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
if (visible(circles[i])) {
circles[i].draw(ctx);
}
}
}
function init() {
canvas = document.getElementById("space");
ctx = canvas.getContext('2d');
blackhole = new Ball(pixel_Rs, {
x: 700,
y: 400
}, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * 1400), Math.floor(Math.random() * 800));
circle = new Ball(5, vec2D, ccolor);
circles.push(circle);
}
drawEverything();
requestAnimationFrame(update);
}
function Ball(radius, position, color) {
this.radius = radius;
this.position = position;
this.color = color;
}
//
Ball.prototype.draw = function(ctx) {
var c=parseInt(this.color);
ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',1)';
ctx.beginPath();
ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
};
function Vector2D(x, y) {
this.x = x;
this.y = y;
}
init();
body{ background-color: #021c36; margin: 0px; }
<canvas id="space" width=1400 height=800></canvas>
Simple solution:
In drawEverything() function move blackhole.draw(ctx) to be the last step
Not so simple: Use one of the many JS particle systems

Html5 canvas image on click

I'm having a problem whit my code.
I draw some circles in a circular path and I expect when to click on them to return something other than 0 in firebug console but that's not happening;
I don't know what is wrong with my code and i hope someone will tell me.
Here's my code:
var canvas, ctx;
var circle_data = [];
function circles(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function (context) {
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2 * Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
function draw() {
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI / 180);
var x = Math.sin(radi * n * 36) * 70;
var y = Math.cos(radi * n * 36) * 70;
var radius = 50;
var thiscircle = new circles(x, y, radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e) {
var img_data = ctx.getImageData(e.pageX, e.pageY, 1, 1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
It dosen't matter is i use data[3];
I tried whit console.log(img_data.data[0]+" "+img_data.data[1]+" "+img_data.data[2]);
Still getting 0 0 0
Your detecting the mouse position relative to the page and not the canvas, you need to get the position of the canvas on the page and subtract that from the X and Y of the mouse to find you position relative to the canvas. I use functions similar to the ones below when working with canvas.
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
The following code works.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<canvas id="canvas" width="500" height="500" style="background-color:#999999;"></canvas>
</body>
<script>
var canvas,ctx;
var circle_data = [];
function circles(x,y,radius)
{
this.x = x;
this.y = y;
this.radius = radius;
circle_data.push(this);
}
circles.prototype = {
draw: function(context){
context.beginPath();
context.arc(this.x, this.y, this.radius / 5, 0, 2* Math.PI, false);
context.fillStyle = "red";
context.fill();
}
}
getOffsetPosition = function(obj){
/*obj is the Canvas element*/
var offsetX = offsetY = 0;
if (obj.offsetParent) {
do {
offsetX += obj.offsetLeft;
offsetY += obj.offsetTop;
}while(obj = obj.offsetParent);
}
return [offsetX,offsetY];
}
getMouse = function(e,canvasElement){
OFFSET = getOffsetPosition(canvasElement);
mouse_x = (e.pageX || (e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft)) - OFFSET[0];
mouse_y = (e.pageY || (e.clientY + document.body.scrollTop + document.documentElement.scrollTop)) - OFFSET[1];
return [mouse_x,mouse_y];
}
function draw(){
ctx.translate(250, 250);
for (var n = 0; n < 10; n++) {
var radi = (Math.PI/180);
var x = Math.sin(radi*n*36)*70;
var y = Math.cos(radi*n*36)*70;
var radius = 50;
var thiscircle = new circles(x,y,radius);
thiscircle.draw(ctx);
}
}
function mouseDown(e)
{
var pos = getMouse(e,ctx.canvas);
var img_data = ctx.getImageData(pos[0],pos[1],1,1);
console.log(img_data.data[3]);
}
function init() {
canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
draw();
canvas.addEventListener('mousedown', mouseDown, false);
}
init();
</script>
</html>

Categories

Resources