Animate image randomly size continously - javascript

The last topic about random moving is answered. But one of my question still not answered yet. About how to create random image size like this : http://ie.microsoft.com/testdrive/Performance/FishIETank/
So what i need? Math.random and for? Please suggest :)
Here's what i've work : http://jsfiddle.net/t9tvnvot/1/
function track(circle, horizontal,vertical,randomly) {
(....)
randomly[0] = Math.random * (circleX + Math.cos(length) * radius); //when i put this, the animation go crazy move
randomly[1] = Math.random * (circleX + Math.sin(length) * radius); //
}
Help & teach me please :)

I think it is prety simple....
Try changing Math.random to Math.random() and it should work...
function track(circle, horizontal,vertical,randomly) {
(....)
randomly[0] = Math.random() * (circleX + Math.cos(length) * radius);
randomly[1] = Math.random() * (circleX + Math.sin(length) * radius);
}
Here is the edited code from the fiddle (this code generate a new position for the butterfly every time, can be far away):
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var circleX = 200;
var circleY = 200;
var radius = 150;
var length = 0;
var setX = 0;
var setY = 0;
var speed = 0.1;
function track(circle, horizontal,vertical) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "red";
context.strokeRect(5, 5, 490, 490);
//circle track move
circle[0] = Math.random() * (circleX + Math.cos(length) * radius);
circle[1] = Math.random() * (circleY + Math.sin(length) * radius);
length += speed;
context.beginPath();
var img = new Image();
img.src = "http://es.fordesigner.com/imguploads/Image/cjbc/zcool/png20080526/1211766513.png";
context.drawImage(img, circle[0], circle[1], circle[2], circle[3]);
context.fill();
}
setInterval(function () {
track
([setX, setY, 50, 50], [setX, setY, 50, 50], [setX,setY, 50, 50]);}, 300);
See also that i increase the time of the interval funtion so it does look so messy...
This is another example but this code the butterfly only appears in the vecinity of the previous position so it doesn seem to desapear:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var length = 0;
var x = 250;
var y = 250;
var setX = 0;
var setY = 0;
var speed = 0.1;
function track(circle, horizontal, vertical) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "red";
context.strokeRect(5, 5, 490, 490);
//movement
if (x >= 0) {
if (x <= 450) {
if (y >= 0) {
if (y <= 450) {
if (Math.floor(Math.random() * 4) == 0) {
x = x + Math.random() + 15;
}
if (Math.floor(Math.random() * 4) == 2) {
y = y + Math.random() + 15;
}
if (Math.floor(Math.random() * 4) == 1) {
x = x - Math.random() - 15;
}
if (Math.floor(Math.random() * 4) == 3) {
y = y - Math.random() - 15;
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > 450) {
x = 450;
}
if (y > 450) {
y = 450;
}
circle[0] = x;
circle[1] = y;
length += speed;
context.beginPath();
var img = new Image();
img.src = "http://es.fordesigner.com/imguploads/Image/cjbc/zcool/png20080526/1211766513.png";
context.drawImage(img, circle[0], circle[1], circle[2], circle[3]);
context.fill();
}
}
}
}
}
setInterval(function () {
track([setX, setY, 50, 50], [setX, setY, 500, 500], [setX, setY, 50, 50]);
}, 30);
According to your comment you want the butterfly to change also size,
here is the new code:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var length = 0;
var x = 250;
var y = 250;
var z = 50;
var setX = 0;
var setY = 0;
var speed = 0.1;
function track(circle, horizontal, vertical) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "red";
context.strokeRect(5, 5, 490, 490);
//movement
if (x >= 0) {
if (x <= 450) {
if (y >= 0) {
if (y <= 450) {
if (Math.floor(Math.random() * 4) == 0) {
x = x + Math.random() + 15;
z = z-15;
}
if (Math.floor(Math.random() * 4) == 2) {
y = y + Math.random() + 15;
z = z-15;
}
if (Math.floor(Math.random() * 4) == 1) {
x = x - Math.random() - 15;
z = z+15;
}
if (Math.floor(Math.random() * 4) == 3) {
y = y - Math.random() - 15;
z = z+10;
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > 450) {
x = 450;
}
if (y > 450) {
y = 450;
}
if (z<20){
z=20;
}
if (z>100){
z=100;
}
circle[0] = x;
circle[1] = y;
circle[3] = z;
circle[2] = z;
length += speed;
context.beginPath();
var img = new Image();
img.src = "http://es.fordesigner.com/imguploads/Image/cjbc/zcool/png20080526/1211766513.png";
context.drawImage(img, circle[0], circle[1], circle[2], circle[3]);
context.fill();
}
}
}
}
}
setInterval(function () {
track([setX, setY, 50, 50], [setX, setY, 500, 500], [setX, setY, 50, 50]);
}, 60);
I just added the math.random with upper(100) and lower limit(20) to the circle[3] and circle[2].
Hope it helps...

Related

Select a new number from array every second randomly

var canvas = document.createElement("canvas");
b = canvas.getContext("2d");
canvas.id = "canvas"
canvas.width = 900;
canvas.height = 600;
document.body.appendChild(canvas);
var posX = 430;
posY = 300;
var myArray = [-3.5,0,3.5];
var dX = myArray[Math.floor(Math.random()*myArray.length)];
var dY = myArray[Math.floor(Math.random()*myArray.length)];
setInterval(function (){
b.fillStyle = "steelblue";
b.fillRect(0, 0, canvas.width, canvas.height);
posX += dX;
posY += dY;
if (posX > 875){
dX = 0;
posX = 875;
}
if (posX < 5){
dx = 0;
posX = 5;
}
if (posY > 575){
dY = 0;
posY = 575;
}
if (posY < 5){
dY = 0;
posY = 5;
}
b.fillStyle = "snow";
b.fillRect(posX, posY, 20, 20);
}, 20)
This is all my Code. I want to move the cube on the background randomly. Right now it moves in just one random direction. but I want it to change this direction every second. for that dX and dY have to change every each second.
Do it this way:
If you have any questions about the code. Feel free to write a comment.
const canvas = document.createElement('canvas')
canvas.width = 100
canvas.height = 100
canvas.style.backgroundColor = 'steelblue'
document.body.appendChild(canvas)
const ctx = canvas.getContext('2d')
const RADIUS = 5
const SPEED = 0.6
let pos = [canvas.width / 2, canvas.height / 2]
let direction = [0, 0]
setInterval(function() {
pos[0] += direction[0] * SPEED
pos[1] += direction[1] * SPEED
if(pos[0] <= RADIUS || pos[0] >= canvas.width - RADIUS ||
pos[1] <= RADIUS || pos[1] >= canvas.height - RADIUS) {
pos = [canvas.width / 2, canvas.height / 2]
}
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.fillStyle = "snow"
ctx.fillRect(pos[0] - RADIUS, pos[1] - RADIUS, 2 * RADIUS, 2 * RADIUS)
}, 20)
setInterval(function() {
const randomAngle = Math.random() * 2 * Math.PI
direction = [Math.cos(randomAngle), Math.sin(randomAngle)]
}, 1000)
use setInterval() https://javascript.info/settimeout-setinterval
var myArray = [-3.5,0,3.5];
var dX, dY
setInterval(() => {
dX = myArray[Math.floor(Math.random()*myArray.length)];
dY = myArray[Math.floor(Math.random()*myArray.length)];
}, 1000)
I would personally opt to use Array.prototype to add a method which will get a random element of the array, and then use setInterval to update the values evey second:
Array.prototype.getRandom = function() {
let index = Math.floor(Math.random() * this.length);
return this[index];
}
var myArray = [-3.5,0,3.5];
var dX, dY;
function updateDerivatives() {
dX = myArray.getRandom(),
dY = myArray.getRandom();
console.log("Updated values:", { dX, dY });
}
setInterval(updateDerivatives, 1000);
var myArray = [-3.5,0,3.5];
var dX;
var dY;
setInterval(() => { // you could also use setInterval(function(){...},...)
dX = myArray[Math.floor(Math.random()*myArray.length)];
dY = myArray[Math.floor(Math.random()*myArray.length)];
}, 1000) // 1000 milliseconds

Canvas Fade Out Particles

I'm a canvas beginner, sorry if this is a trivial question. How can I make the fireworks in my work fade out once they've exploded?
https://jsfiddle.net/ccwhryvv/
var SCREEN_WIDTH = window.innerWidth,
SCREEN_HEIGHT = window.innerHeight,
mousePos = {
x: 400,
y: 300
},
// create canvas
canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
particles = [],
rockets = [],
MAX_PARTICLES = 400,
colorCode = 0;
// init
$(document).ready(function() {
$('#content')[0].appendChild(canvas);
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
setInterval(launch, 800);
setInterval(loop, 1000 / 50);
});
// update mouse position
$(document).mousemove(function(e) {
e.preventDefault();
mousePos = {
x: e.clientX,
y: e.clientY
};
});
// launch more rockets!!!
$(document).mousedown(function(e) {
for (var i = 0; i < 5; i++) {
launchFrom(Math.random() * SCREEN_WIDTH * 2 / 3 + SCREEN_WIDTH / 6);
}
});
function launch() {
launchFrom(SCREEN_WIDTH / 2);
}
function launchFrom(x) {
if (rockets.length < 10) {
var rocket = new Rocket(x);
rocket.explosionColor = Math.floor(Math.random() * 360 / 10) * 10;
rocket.vel.y = Math.random() * -3 - 4;
rocket.vel.x = Math.random() * 6 - 3;
rocket.size = 8;
rocket.shrink = 0.999;
rocket.gravity = 0.01;
rockets.push(rocket);
}
}
function loop() {
// update screen size
if (SCREEN_WIDTH != window.innerWidth) {
canvas.width = SCREEN_WIDTH = window.innerWidth;
}
if (SCREEN_HEIGHT != window.innerHeight) {
canvas.height = SCREEN_HEIGHT = window.innerHeight;
}
// clear canvas
context.fillStyle = "rgba(0, 0, 0, 0.0)";
context.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
var existingRockets = [];
for (var i = 0; i < rockets.length; i++) {
// update and render
rockets[i].update();
rockets[i].render(context);
// calculate distance with Pythagoras
var distance = Math.sqrt(Math.pow(mousePos.x - rockets[i].pos.x, 2) + Math.pow(mousePos.y - rockets[i].pos.y, 2));
// random chance of 1% if rockets is above the middle
var randomChance = rockets[i].pos.y < (SCREEN_HEIGHT * 2 / 3) ? (Math.random() * 100 <= 1) : false;
/* Explosion rules
- 80% of screen
- going down
- close to the mouse
- 1% chance of random explosion
*/
if (rockets[i].pos.y < SCREEN_HEIGHT / 5 || rockets[i].vel.y >= 0 || distance < 50 || randomChance) {
rockets[i].explode();
} else {
existingRockets.push(rockets[i]);
}
}
rockets = existingRockets;
var existingParticles = [];
for (var i = 0; i < particles.length; i++) {
particles[i].update();
// render and save particles that can be rendered
if (particles[i].exists()) {
particles[i].render(context);
existingParticles.push(particles[i]);
}
}
// update array with existing particles - old particles should be garbage collected
particles = existingParticles;
while (particles.length > MAX_PARTICLES) {
particles.shift();
}
}
function Particle(pos) {
this.pos = {
x: pos ? pos.x : 0,
y: pos ? pos.y : 0
};
this.vel = {
x: 0,
y: 0
};
this.shrink = .97;
this.size = 2;
this.resistance = 1;
this.gravity = 0;
this.flick = false;
this.alpha = 1;
this.fade = 0;
this.color = 0;
}
Particle.prototype.update = function() {
// apply resistance
this.vel.x *= this.resistance;
this.vel.y *= this.resistance;
// gravity down
this.vel.y += this.gravity;
// update position based on speed
this.pos.x += this.vel.x;
this.pos.y += this.vel.y;
// shrink
this.size *= this.shrink;
// fade out
this.alpha -= this.fade;
};
Particle.prototype.render = function(c) {
if (!this.exists()) {
return;
}
c.save();
c.globalCompositeOperation = 'lighter';
var x = this.pos.x,
y = this.pos.y,
r = this.size / 2;
var gradient = c.createRadialGradient(x, y, 0.1, x, y, r);
gradient.addColorStop(0.1, "rgba(255,255,255," + this.alpha + ")");
gradient.addColorStop(0.8, "hsla(" + this.color + ", 100%, 50%, " + this.alpha + ")");
gradient.addColorStop(1, "hsla(" + this.color + ", 100%, 50%, 0.1)");
c.fillStyle = gradient;
c.beginPath();
c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size : this.size, 0, Math.PI * 2, true);
c.closePath();
c.fill();
c.restore();
};
Particle.prototype.exists = function() {
return this.alpha >= 0.1 && this.size >= 1;
};
function Rocket(x) {
Particle.apply(this, [{
x: x,
y: SCREEN_HEIGHT}]);
this.explosionColor = 0;
}
Rocket.prototype = new Particle();
Rocket.prototype.constructor = Rocket;
Rocket.prototype.explode = function() {
var count = Math.random() * 10 + 80;
for (var i = 0; i < count; i++) {
var particle = new Particle(this.pos);
var angle = Math.random() * Math.PI * 2;
// emulate 3D effect by using cosine and put more particles in the middle
var speed = Math.cos(Math.random() * Math.PI / 2) * 15;
particle.vel.x = Math.cos(angle) * speed;
particle.vel.y = Math.sin(angle) * speed;
particle.size = 10;
particle.gravity = 0.2;
particle.resistance = 0.92;
particle.shrink = Math.random() * 0.05 + 0.93;
particle.flick = true;
particle.color = this.explosionColor;
particles.push(particle);
}
};
Rocket.prototype.render = function(c) {
if (!this.exists()) {
return;
}
c.save();
c.globalCompositeOperation = 'lighter';
var x = this.pos.x,
y = this.pos.y,
r = this.size / 2;
var gradient = c.createRadialGradient(x, y, 0.1, x, y, r);
gradient.addColorStop(0.1, "rgba(255, 255, 255 ," + this.alpha + ")");
// gradient.addColorStop(1, "rgba(255, 255, 255, " + this.alpha + ")");
gradient.addColorStop(1, "rgba(255, 255, 255, 0)");
c.fillStyle = gradient;
c.beginPath();
c.arc(this.pos.x, this.pos.y, this.flick ? Math.random() * this.size / 2 + this.size / 2 : this.size, 0, Math.PI * 2, true);
c.closePath();
c.fill();
c.restore();
};
Thank you!
Creating gradients is expensive -- especially inside an animation loop.
It's more efficient is to pre-create a spritesheet of gradient exploding sprites before your app starts:
Create an in-memory canvas to act as a spritesheet,
Choose a dozen standard colors for you explosions.
Create gradient sprites in sequential order of exploding.
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var ss=makeSpritesheet(10,15);
ctx.fillStyle='navy';
ctx.fillRect(0,0,cw,ch);
ctx.drawImage(ss,0,0);
function makeSpritesheet(maxRadius,colorCount){
var c=document.createElement('canvas');
var ctx=c.getContext('2d');
var spacing=maxRadius*2.5;
c.width=spacing*maxRadius;
c.height=spacing*(colorCount+1);
for(var colors=0;colors<colorCount;colors++){
var y=(colors)*spacing+spacing/2;
var color = parseInt(colors/colorCount*360);
for(r=2;r<=maxRadius;r++){
var x=(r-1)*spacing;
var gradient = ctx.createRadialGradient(x, y, 0, x, y, r);
gradient.addColorStop(0.2, "white");
gradient.addColorStop(0.7, 'hsla('+color+', 100%, 50%, 1)');
gradient.addColorStop(1.0, "rgba(0,0,0,0)");
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2);
ctx.closePath();
ctx.fill();
}
}
return(c);
}
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=640 height=512></canvas>
During Animation, draw the sprites from the spritesheet to your canvas.
Fade the opacity of each sprite by setting context.globalAlpha before drawing each sprite.

how can i make two objects belonging to the same array move independently of each other using javascript and the canvas tag?

I am trying to create a blackhole simulation, where all the balls that are outside of it go away from it at a given speed and those that fall on it are dragged towards the circle until they reach the center of it, where they would stop and disappear, here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>blackhole simulation escape velocity</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-5 ) {
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 {
var delta2 = new Vector2D (0,0);
var forceDirection2 = Math.atan2(pos.y - 400, pos.x - 700);
var g = (pixel_G*pixel_M)/(distance*distance*1e2);
delta2.x += Math.cos(forceDirection2)*g;
delta2.y += Math.sin(forceDirection2)*g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == 700 && pos.y == 400){
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
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;
}
function onClick (){
canvas = document.getElementById ('space');
ctx = canvas.getContext ('2d')
canvas.addEventListener ("mousedown", init, false)
blackhole = new Ball (5, {x: 700,
y: 400 }, 0);
blackhole.draw (ctx) ;
}
window.onload = onClick;
</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 second variable called delta2, but the problem is that it can't update the position of the circles, which in term makes it impossible to move the circle, can someone tell me what is wrong. Also, how can I make the big black circle after a certain amount of time, i know i probably should create a timer, but i don't know how they work
The gravity is too weak. I put a pseudo gravity to demonstrate.
var canvas, ctx;
var blackhole;
var circle;
var circles = new Array();
var bh = {
w:500,
h:300
};
bh.cx = Math.floor(bh.w/2);
bh.cy = Math.floor(bh.h/2)
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 - bh.cx) * (pos.x - bh.cx)) + ((pos.y - bh.cy) * (pos.y - bh.cy)));
if (distance > pixel_Rs - 5) {
var delta = new Vector2D(0, 0);
var forceDirection = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
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 {
var delta2 = new Vector2D(0, 0);
var forceDirection2 = Math.atan2(pos.y - bh.cy, pos.x - bh.cx);
// FIX THIS!!!
var g = 1;//(pixel_G * pixel_M) / (distance * distance * 1e2);
delta2.x += Math.cos(forceDirection2) * g;
delta2.y += Math.sin(forceDirection2) * g;
pos.x -= delta2.x;
pos.y -= delta2.y;
somethingMoved = true;
circles[i].color -= 1;
if (pos.x == bh.cx && pos.y == bh.cy) {
somethingMoved = false;
};
}
}
if (somethingMoved) {
drawEverything();
requestAnimationFrame(update);
};
}
function drawEverything() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
blackhole.draw(ctx);
for (var i = 0; i < circles.length; i++) {
circles[i].draw(ctx);
}
}
function init(event) {
canvas = document.getElementById("space");
canvas.width = bh.w;
canvas.height = bh.h;
ctx = canvas.getContext('2d');
blackhole = new Ball(5, { //pixel_Rs, {
x: bh.cx,
y: bh.cy
}, 0);
for (var i = 0; i < 200; i++) {
var vec2D = new Vector2D(Math.floor(Math.random() * bh.w), Math.floor(Math.random() * bh.h));
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;
}
function onClick() {
canvas = document.getElementById('space');
ctx = canvas.getContext('2d')
canvas.addEventListener("mousedown", init, false)
blackhole = new Ball(5, {
x: bh.cx,
y: bh.cy
}, 0);
blackhole.draw(ctx);
}
window.onload = onClick;
body {
background-color: #021c36;
margin: 0px;
}
<canvas id="space" , width="700" , height="400"></canvas>

Circle animation random color

Hi I try to create an animation with a circle. The function drawRandom(drawFunctions) should pic one of the three drawcircle functions and should bring it on the canvas. Now the problem is that this function become executed every second (main loop) and the circle change his colour. How can I fix that?
window.onload = window.onresize = function() {
var C = 1; // canvas width to viewport width ratio
var el = document.getElementById("myCanvas");
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * C;
var canvasHeight = viewportHeight;
el.style.position = "fixed";
el.setAttribute("width", canvasWidth);
el.setAttribute("height", canvasHeight);
var x = canvasWidth / 100;
var y = canvasHeight / 100;
var ballx = canvasWidth / 100;
var n;
window.ctx = el.getContext("2d");
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// draw triangles
function init() {
ballx;
return setInterval(main_loop, 1000);
}
function drawcircle1()
{
var radius = x * 5;
ctx.beginPath();
ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'yellow';
ctx.fill();
}
function drawcircle2()
{
var radius = x * 5;
ctx.beginPath();
ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();
}
function drawcircle3()
{
var radius = x * 5;
ctx.beginPath();
ctx.arc(ballx * 105, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'orange';
ctx.fill();
}
function draw() {
var counterClockwise = false;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
//first halfarc
ctx.beginPath();
ctx.arc(x * 80, y * 80, y * 10, 0 * Math.PI, 1 * Math.PI, counterClockwise);
ctx.lineWidth = y * 1;
ctx.strokeStyle = 'black';
ctx.stroke();
// draw stop button
ctx.beginPath();
ctx.moveTo(x * 87, y * 2);
ctx.lineTo(x * 87, y * 10);
ctx.lineWidth = x;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x * 95, y * 2);
ctx.lineTo(x * 95, y * 10);
ctx.lineWidth = x;
ctx.stroke();
function drawRandom(drawFunctions){
//generate a random index
var randomIndex = Math.floor(Math.random() * drawFunctions.length);
//call the function
drawFunctions[randomIndex]();
}
drawRandom([drawcircle1, drawcircle2, drawcircle3]);
}
function update() {
ballx -= 0.1;
if (ballx < 0) {
ballx = -radius;
}
}
function main_loop() {
draw();
update();
collisiondetection();
}
init();
function initi() {
console.log('init');
// Get a reference to our touch-sensitive element
var touchzone = document.getElementById("myCanvas");
// Add an event handler for the touchstart event
touchzone.addEventListener("mousedown", touchHandler, false);
}
function touchHandler(event) {
// Get a reference to our coordinates div
var can = document.getElementById("myCanvas");
// Write the coordinates of the touch to the div
if (event.pageX < x * 50 && event.pageY > y * 10) {
ballx += 1;
} else if (event.pageX > x * 50 && event.pageY > y * 10 ) {
ballx -= 1;
}
console.log(event, x, ballx);
draw();
}
initi();
draw();
}
Take a look at my code that I wrote:
var lastTime = 0;
function requestMyAnimationFrame(callback, time)
{
var t = time || 16;
var currTime = new Date().getTime();
var timeToCall = Math.max(0, t - (currTime - lastTime));
var id = window.setTimeout(function(){ callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 20;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
var circles = [];
var mouse =
{
x: 0,
y: 0
}
function getCoordinates(x, y)
{
return "(" + x + ", " + y + ")";
}
function getRatio(n, d)
{
// prevent division by 0
if (d === 0 || n === 0)
{
return 0;
}
else
{
return n/d;
}
}
function Circle(x,y,d,b,s,c)
{
this.x = x;
this.y = y;
this.diameter = Math.round(d);
this.radius = Math.round(d/2);
this.bounciness = b;
this.speed = s;
this.color = c;
this.deltaX = 0;
this.deltaY = 0;
this.drawnPosition = "";
this.fill = function()
{
context.beginPath();
context.arc(this.x+this.radius,this.y+this.radius,this.radius,0,Math.PI*2,false);
context.closePath();
context.fill();
}
this.clear = function()
{
context.fillStyle = "#ffffff";
this.fill();
}
this.draw = function()
{
if (this.drawnPosition !== getCoordinates(this.x, this.y))
{
context.fillStyle = this.color;
// if commented, the circle will be drawn if it is in the same position
//this.drawnPosition = getCoordinates(this.x, this.y);
this.fill();
}
}
this.keepInBounds = function()
{
if (this.x < 0)
{
this.x = 0;
this.deltaX *= -1 * this.bounciness;
}
else if (this.x + this.diameter > canvas.width)
{
this.x = canvas.width - this.diameter;
this.deltaX *= -1 * this.bounciness;
}
if (this.y < 0)
{
this.y = 0;
this.deltaY *= -1 * this.bounciness;
}
else if (this.y+this.diameter > canvas.height)
{
this.y = canvas.height - this.diameter;
this.deltaY *= -1 * this.bounciness;
}
}
this.followMouse = function()
{
// deltaX/deltaY will currently cause the circles to "orbit" around the cursor forever unless it hits a wall
var centerX = Math.round(this.x + this.radius);
var centerY = Math.round(this.y + this.radius);
if (centerX < mouse.x)
{
// circle is to the left of the mouse, so move the circle to the right
this.deltaX += this.speed;
}
else if (centerX > mouse.x)
{
// circle is to the right of the mouse, so move the circle to the left
this.deltaX -= this.speed;
}
else
{
//this.deltaX = 0;
}
if (centerY < mouse.y)
{
// circle is above the mouse, so move the circle downwards
this.deltaY += this.speed;
}
else if (centerY > mouse.y)
{
// circle is under the mouse, so move the circle upwards
this.deltaY -= this.speed;
}
else
{
//this.deltaY = 0;
}
this.x += this.deltaX;
this.y += this.deltaY;
this.x = Math.round(this.x);
this.y = Math.round(this.y);
}
}
function getRandomDecimal(min, max)
{
return Math.random() * (max-min) + min;
}
function getRoundedNum(min, max)
{
return Math.round(getRandomDecimal(min, max));
}
function getRandomColor()
{
// array of three colors
var colors = [];
// go through loop and add three integers between 0 and 255 (min and max color values)
for (var i = 0; i < 3; i++)
{
colors[i] = getRoundedNum(0, 255);
}
// return rgb value (RED, GREEN, BLUE)
return "rgb(" + colors[0] + "," + colors[1] + ", " + colors[2] + ")";
}
function createCircle(i)
{
// diameter of circle
var minDiameter = 25;
var maxDiameter = 50;
// bounciness of circle (changes speed if it hits a wall)
var minBounciness = 0.2;
var maxBounciness = 0.65;
// speed of circle (how fast it moves)
var minSpeed = 0.3;
var maxSpeed = 0.45;
// getRoundedNum returns a random integer and getRandomDecimal returns a random decimal
var x = getRoundedNum(0, canvas.width);
var y = getRoundedNum(0, canvas.height);
var d = getRoundedNum(minDiameter, maxDiameter);
var c = getRandomColor();
var b = getRandomDecimal(minBounciness, maxBounciness);
var s = getRandomDecimal(minSpeed, maxSpeed);
// create the circle with x, y, diameter, bounciness, speed, and color
circles[i] = new Circle(x,y,d,b,s,c);
}
function makeCircles()
{
var maxCircles = getRoundedNum(2, 5);
for (var i = 0; i < maxCircles; i++)
{
createCircle(i);
}
}
function drawCircles()
{
var ii = 0;
for (var i = 0; ii < circles.length; i++)
{
if (circles[i])
{
circles[i].draw();
ii++;
}
}
}
function clearCircles()
{
var ii = 0;
for (var i = 0; ii < circles.length; i++)
{
if (circles[i])
{
circles[i].clear();
ii++;
}
}
}
function updateCircles()
{
var ii = 0;
for (var i = 0; ii < circles.length; i++)
{
if (circles[i])
{
circles[i].keepInBounds();
circles[i].followMouse();
ii++;
}
}
}
function update()
{
requestMyAnimationFrame(update,10);
updateCircles();
}
function draw()
{
requestMyAnimationFrame(draw,1000/60);
context.clearRect(0,0,canvas.width,canvas.height);
drawCircles();
}
window.addEventListener("load", function()
{
window.addEventListener("mousemove", function(e)
{
mouse.x = e.layerX || e.offsetX;
mouse.y = e.layerY || e.offsetY;
});
makeCircles();
update();
draw();
});

mouseover events with canvas

I was wondering if it was possible to have mouseover events with multiple squares on a canvas
this is my code right now: http://jsfiddle.net/2j3u9f7m/
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var Enemy = function (x, y, velx, vely) {
this.x = x;
this.y = y;
this.velx = 0;
this.vely = 0;
}
Enemy.prototype.update = function () {
var tx = 650 - this.x;
var ty = 250 - this.y;
var dist = Math.sqrt(tx * tx + ty * ty);
this.velx = (tx / dist);
this.vely = (ty / dist);
if (dist > 0) {
this.x += this.velx;
this.y += this.vely;
}
};
Enemy.prototype.render = function () {
context.fillStyle = '#000000';
context.beginPath();
context.rect(this.x, this.y, 25, 25);
context.fill();
context.closePath();
};
var enemies = [];
for (var i = 0; i < 10; i++) {
// random numbers from 0 (inclusive) to 100 (exclusive) for example:
var randomX = Math.random() * 896;
var randomY = Math.random() * 1303;
console.log(randomX);
console.log(randomY);
if (randomX > 100 && randomX < 1200) {
if (randomX % 2 == 0) {
randomX = 140;
} else {
randomX = 1281;
}
}
if (randomY > 100 && randomY < 75) {
if (randomY % 2 == 0) {
randomY = 15;
} else {
randomY = 560;
}
}
var enemy = new Enemy(randomX, randomY, 0, 0);
enemies.push(enemy);
}
for (var i = 0; i < 15; i++) {
// random numbers from 0 (inclusive) to 100 (exclusive) for example:
var randomX = Math.random() * 200;
var randomY = Math.random() * 403;
console.log(randomX);
console.log(randomY);
if (randomX > 100 && randomX < 1200) {
if (randomX % 2 == 0) {
randomX = 140;
} else {
randomX = 1281;
}
}
if (randomY > 100 && randomY < 75) {
if (randomY % 2 == 0) {
randomY = 15;
} else {
randomY = 560;
}
}
var enemy = new Enemy(randomX, randomY, 0, 0);
enemies.push(enemy);
}
function render() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < enemies.length; i++) {
var one = enemies[i];
one.update();
one.render();
}
requestAnimationFrame(render);
}
render();
What I want to do is to have a mouseover event for each square; is there a way to do this without using a library?
You can extend your Enemy object doing a region check like this:
Enemy.prototype.isOnEnemy = function(x, y) {
return (x >= this.x && x < this.x + 25 && // 25 = width
y >= this.y && y < this.y + 25); // 25 = height
};
If the provided (x,y) position is inside the rectangle (here assuming width and height of 25) it will return true.
Then add a mousemove event listener to the canvas. Inside adjust the mouse position, then feed the muse position to each enemy object to check:
context.canvas.onmousemove = function(e) {
var rect = this.getBoundingClientRect(), // correct mouse position
x = e.clientX - rect.left,
y = e.clientY - rect.top,
i = 0;
for(; i < enemies.length; i++) { // check each enemy
if (enemies[i].isOnEnemy(x, y)) { // is inside?
console.log("AAAARG...", i); // some action...
}
}
};
Modified fiddle (see console for hits).

Categories