loop object over canvas JS P5 - javascript

I use JS P5.
I've created a function that creates an ellipse.
I want to loop this ellipse over the whole canvas with some distance between each ellipse.
I didn't use a normal ellipse because I want to put another function on each ellipse later.
So my question how to use a for loop and a nested loop on an object that I create.
This is my code, I have a random way here, but I want is the exact distance, like a grid over the whole page.
Like this example
let shapes = [];
function setup() {
createCanvas(600, 600);
for (let i = 0; i < 500; i++){
let x = random(width);
let y = random(height);
shapes[i] = new shape(x,y,20);
}
}
function draw() {
background(220);
for (let i = 0; i < shapes.length; i++){
shapes[i].display();
}
}
function shape(tx, ty, ts) {
this.x = tx;
this.y = ty;
this.size = ts;
this.angle = 0;
this.update = function(mx, my) {
this.angle = atan2(my - this.y, mx - this.x);
};
this.display = function() {
push();
fill(153, 204, 0);
ellipse(this.x, this.y, this.size, this.size);
pop();
};
}

Edited answer:
let shapes = [];
function setup() {
createCanvas(600, 600);
for(var x=0;x<width;x+=30){
for(var y=0;y<height;y+=30){
shapes.push(new shape(x,y,20));
}
}
}
function draw() {
background(220);
for (let i = 0; i < shapes.length; i++){
shapes[i].display();
}
}
function shape(tx, ty, ts) {
this.x = tx;
this.y = ty;
this.size = ts;
this.angle = 0;
this.update = function(mx, my) {
this.angle = atan2(my - this.y, mx - this.x);
};
this.display = function() {
push();
fill(153, 204, 0);
ellipse(this.x, this.y, this.size, this.size);
pop();
};
}

Related

P5.js how to do 8 directional lerp color/color change?

A last issue i have in this code is that i am not sure how to create color change effect as 8 directional.
I can only map a mouseX to make it lerpColor horizontally or vertically .
But how do i make it work through moving both mouseX and mouseY?
I had it in shift_Color method within the class. I tried to state that within a certain dist(), lerpColor. But now it only showing black color rather than the changing color effect.
let cubes = [];
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
backCol = color(243, 243, 243);
//background(backCol);
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
let xPos = map(i, 0, 9, 50, width - 50);
let yPos = map(j, 0, 9, 50, height - 50);
cubes.push(new Cubes(xPos, yPos));
}
}
}
function draw() {
background(backCol);
noFill();
for (let a = 0; a < cubes.length; a++) {
cubes[a].update();
}
}
class Cubes {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 30;
this.stroke = 70;
this.gap = 110
this.shift1 = color(96);
this.shift2 = color(244);
}
update() {
this.shape();
this.shift_Color();
}
shape() {
push();
stroke(this.stroke);
//fill(this.shift1);
this.shift_Color();
translate(this.x - width / 2, this.y - height / 2, 0);
this.magnetic()
box(this.size);
pop();
}
shift_Color() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.shift1 = color(96);
this.shift2 = color(244);
this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
fill(this.change);
} else {
fill(this.shift1);
}
}
magnetic() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.attract = atan2(mouseY - this.y, mouseX - this.x);
rotateX(this.attract);
rotateY(this.attract);
} else {
rotateX(millis() / 1000);
rotateY(millis() / 1000);
}
}
}
If I understood your question properly, there are two problems in your code.
The first is the fact that because you are trying to map the distance between mouse and the cube to number between 0 and 1, you should write lerpColor(this.shift2, this.shift1, this.shiftX) instead of lerpColor(this.shift1, this.shift2, this.shiftX), since this.shift2 is the lighter color and will be the inner color.
Another problem is when mapping the change variable, change should be calculated based on the distance between mouse and the cube (which is the distance variable), not mouseX or mouseY. Solution is to simply do map(distance, 0, this.gap, 0, 1);.
let cubes = [];
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
backCol = color(243, 243, 243);
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
let xPos = map(i, 0, 9, 50, width - 50);
let yPos = map(j, 0, 9, 50, height - 50);
cubes.push(new Cubes(xPos, yPos));
}
}
}
function draw() {
background(backCol);
noFill();
for (let cube of cubes) {
cube.update();
}
}
class Cubes {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 30;
this.stroke = 70;
this.gap = 110
this.shift1 = color(96);
this.shift2 = color(244);
}
update() {
this.shape();
this.shift_Color();
}
shape() {
push();
stroke(this.stroke);
//fill(this.shift1);
this.shift_Color();
translate(this.x - width / 2, this.y - height / 2, 0);
this.magnetic()
box(this.size);
pop();
}
shift_Color() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.shiftX = map(distance, 0, this.gap, 0, 1);
// this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
this.change = lerpColor(this.shift2, this.shift1, this.shiftX);
// this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
fill(this.change);
} else {
fill(this.shift1);
}
}
magnetic() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.attract = atan2(mouseY - this.y, mouseX - this.x);
rotateX(this.attract);
rotateY(this.attract);
} else {
rotateX(millis() / 1000);
rotateY(millis() / 1000);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
I also modified some of your code. Like the line
this.shift1 = color(96);
this.shift2 = color(244);
which is not needed currently since neither of these variable changes during execution.

requestAnimationFrame too fast

I am creating simple animation in canvas. I use requestanimationframe to control animation. There is 3 circle. But i can only see 3 circle and animation is too fast. My question is how can i slow my animation and how can show each frame. here is my live link.
const swing = (time) => {
for(var i = 0; i < 3; i++) {
circle[i] = new ball();
circle[i].draw(i, circle[i].color);
}
requestAnimationFrame(swing);
}
requestAnimationFrame(swing);
//swing();
function ball(i){
this.x = random(100, 150);
this.y = random(40, 60);
this.radius = 45;
this.color = getRandomColor(random(1, 30));
this.strokeText = "m"
ctx.clearRect(0, 0, el.width, el.height);
this.draw = function(i, color){
ctx.beginPath();
ctx.font="30px Verdana";
ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.globalAlpha = 0.5;
ctx.strokeText(i,i*this.x,this.y);
ctx.fill();
ctx.closePath();
}
}
Thanks in advance.
Edited:- I am creating something similar like this:- http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010
Just a simple example, let three balls doing some circular motion:
// refer below
// http://codepen.io/jscottsmith/pen/oWyxjp?editors=1010
const el = document.getElementById('canvas'),
ctx = el.getContext('2d');
let circle = [];
el.width = document.body.clientWidth;
el.height = document.body.clientHeight;
const getRandomColor = (i) => {
let count = 30,
color = 1,
hue = (i / count * color) * 360;
return `hsla(${hue}, 100%, 50%, 1)`
}
for (var i = 0; i < 3; i++) {
circle[i] = new ball();
}
let angle = 0;
let speed = 0.02;
const swing = (time) => {
ctx.clearRect(0, 0, el.width, el.height);
for (var i = 0; i < 3; i++) {
circle[i].x = circle[i].x + Math.cos(angle) * 1;
circle[i].y = circle[i].y + Math.sin(angle) * 2;
}
for (var i = 0; i < 3; i++) {
circle[i].draw(i, circle[i].color);
}
angle += speed;
requestAnimationFrame(swing);
}
requestAnimationFrame(swing);
//swing();
function ball(i){
this.x = random(100, 150);
this.y = random(40, 60);
this.radius = 45;
this.color = getRandomColor(random(1, 30));
this.strokeText = "m"
this.draw = function(i, color){
ctx.beginPath();
ctx.font="30px Verdana";
ctx.arc(i*this.x, this.y, this.radius, 0, 2*Math.PI, false);
ctx.fillStyle = color;
ctx.globalAlpha = 0.5;
ctx.strokeText(i,i*this.x,this.y);
ctx.fill();
ctx.closePath();
}
}
function random (num1, num2) {
var max = Math.max(num1, num2);
var min = Math.min(num1, num2);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
#canvas {
width: 600px;
height: 600px;
}
<canvas id="canvas"></canvas>

Particle (made with constructor) expand and fade upon collision

When a user clicks on any particle I want it to expand and fade and upon collision with any other particle and that particle will also expand and fade. Now my problem is that I want to know if there is a way in which I can get those particles (made with constructor in this case) to effect each other when they get collide. Link to Codepen
var bubbles = [];
function setup() {
frameRate(25);
// Creates Canvas
createCanvas(windowWidth, windowHeight);
//Genrates 100 Particles with random a & y
for (var i = 0; i < 80; i++) {
var x = random(width);
var y = random(height);
bubbles[i] = new Bubble(x, y);
}
}
function mousePressed() {
for (var i = 0; i < bubbles.length; i++) {
bubbles[i].clicked();
}
}
function draw() {
clear();
//Adds color and motion
for (var bubble of bubbles) {
fill(bubble.color.red, bubble.color.green, bubble.color.blue);
bubble.move();
bubble.display();
}
}
function Bubble(x, y) {
this.x = x;
this.y = y;
this.wh = 15;
this.speedX = random(1, 5);
this.speedY = random(1, 5);
//Individual Particle Creation
this.display = function() {
noStroke();
ellipse(this.x, this.y, this.wh, this.wh);
};
//Interactivity
this.clicked = function() {
var d = dist(this.x, this.y, mouseX, mouseY);
if (d < 8) {
this.wh = 100;
}
};
//Randomizes colors
this.color = {
red: random(255),
green: random(255),
blue: random(255)
};
//Particle Motion
this.move = function() {
//Motion in X direction
this.x += this.speedX;
//Bouncing back on X-axis
if (this.x > windowWidth || this.x < 0) {
this.speedX = -this.speedX;
}
//Motion in Y Direction
this.y += this.speedY;
//Bouncing back on Y-axis
if (this.y > windowHeight || this.y < 0) {
this.speedY = -this.speedY;
}
};
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
::-webkit-scrollbar{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.js"></script>
Use a nested for loop.
Step 1: Loop over the bubbles. Do this with a for loop.
Step 2: For each bubble, loop over the rest of the bubbles (if you're on bubble 4, start with bubble 5). Do this with another for loop inside the first one.
Step 3: Now that you have two bubbles, do the collision between them.
If you're having trouble getting that working, then please start smaller. Start with a simpler program that just shows two hard-coded bubbles and does collision detection between them.

JavaScript Brick Breaker, Bricks in array aren't being spliced?

I'm having trouble with how I remove bricks. The bricks are part of an array, and the ball continuously runs a for loop checking to see if it's hit any bricks. If it does, it splices that brick from the array. But the bricks don't disappear!
//Helper Functions
function AABBIntersect(ax, ay, aw, ah, bx, by, bw, bh) {
return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah;
}
var ball = {
//A few of the basic variables called by the upcoming function
update: function() {
this.x += this.vel.x;
this.y += this.vel.y;
if (0 > this.y) {
var offset = 0 - this.y;
this.y += 2*offset;
this.vel.y *= -1;
}
if (this.y+this.height > HEIGHT) {
this.serve();
}
if (0 > this.x || this.x+this.size > WIDTH) {
var offset = this.vel.x < 0 ? 0 - this.x : WIDTH - (this.x+this.size);
this.x += 2*offset;
this.vel.x *= -1;
}
if (AABBIntersect(this.x, this.y, this.size, this.size, player.x, player.y, player.width, player.height)) {
var offset = player.y - (this.y+this.size);
this.y += 2*offset;
var n = (this.x+this.size - player.x)/(player.width+this.size);
var phi = 0.25*pi*(2*n - 1);
var smash = Math.abs(phi) > 0.2*pi ? 1.5 : 1;
this.vel.x = smash*this.speed*Math.sin(phi);
this.vel.y = smash*-1*this.speed*Math.cos(phi);
}
for (var i = 0; i < bricks.length; i++) {
var b = bricks[i];
if (AABBIntersect(this.x, this.y, this.width, this.height, b.x, b.y, b.width, b.height)) {
bricks.splice(i, 1);
i--;
bricks.length--;
continue;
}
}
}
}
var bricks = [];
function main() {
canvas = document.createElement("canvas");
canvas.width = WIDTH;
canvas.height = HEIGHT;
ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
keystate = {};
document.addEventListener("keydown", function(evt) {
keystate[evt.keyCode] = true;
});
document.addEventListener("keyup", function(evt) {
delete keystate[evt.keyCode];
} );
init();
var loop = function() {
update();
draw();
window.requestAnimationFrame(loop, canvas);
};
window.requestAnimationFrame(loop, canvas);
}
function init() {
var cols = WIDTH / 40;
player.x = (WIDTH - player.width) / 2;
player.y = HEIGHT - (player.height * 2);
ball.x = (WIDTH - ball.size) / 2;
ball.y = player.y - ball.size;
ball.width = ball.size;
ball.height = ball.size;
ball.serve();
for (var i = 0; i < 7; i++) {
for (var j = 0; j < cols; j++) {
bricks.push({
color: "#f00",
x: 2 + j*40,
y: 2 + i*20,
w: 36,
h: 16
});
}
}
}
function update() {
frames++;
player.update();
ball.update();
}
function draw() {
ctx.fillRect(0, 0, WIDTH, HEIGHT);
ctx.save();
ctx.fillStyle = "#fff";
player.draw();
ball.draw();
for (var i = 0; i < bricks.length; i++) {
ctx.fillStyle = bricks[i].color;
ctx.fillRect(bricks[i].x, bricks[i].y, bricks[i].w, bricks[i].h);
}
ctx.restore();
}
main();
A few issues:
The brick objects do not have width or height properties, but w and h;
The splice should not happen on a brick element (b), but on the array of bricks (bricks);
The length of bricks should not be decremented after the splice, as that operation already reduces the length.
So use this loop:
for (var i = 0; i < bricks.length; i++) {
var b = bricks[i];
if (AABBIntersect(this.x, this.y, this.width, this.height, b.x, b.y, b.w, b.h)) {
bricks.splice(i, 1);
i--;
}
}

How to create mouseover highlight box in html 5?

If I have a 600 by 400 grid, with 10 by 10 pixel squares like this:
/**
* draws grid to screen
*/
function drawgrid(context)
{
for(var x = 0.5; x < 600; x += 10)
{
context.moveTo(x, 0);
context.lineTo(x, 400);
}
for(var y = 0.5; y < 400; y += 10)
{
context.moveTo(0, y);
context.lineTo(600, y);
}
context.strokeStyle = "#eee";
context.stroke();
}
/**
* Creates a canvas element, loads images, adds events, and draws the canvas for the first time.
*/
function prepareCanvas()
{
var context = document.getElementById('canvas').getContext("2d");
drawgrid(context);
}
How would I mouseover the individual squares and highlight the square that the mouse is hovering over. Like make a red box highlighting the grid square the mouse is over.
See code below. Adjust coordinates for event
<body>
<canvas id=canvas height=400 width=600
onmousemove="over()" style="cursor:crosshair">
</canvas>
</body>
<script type="text/javascript">
<!--
var grid;
function prepareCanvasGrid()
{
var cnv = document.getElementById('canvas');
grid = new CanvasGrid(cnv.getContext("2d"),cnv.offsetLeft, cnv.offsetTop);
}
function CanvasGrid(context,x,y) {
this.sq = [];
this.dirty = [];
this.ctx = context;
this.x = x;
this.y = y;
this.init = function(){
for(var x = 0.5; x < 600; x += 50) {
for(var y = 0.5; y < 400; y += 50) {
var s = new square(x,y, context);
this.sq.push(s);
}
}
}
this.draw = function(){
this.ctx.clearRect(0,0,600,400);
for(var i=0; i < this.sq.length; i++)
this.sq[i].draw();
}
this.clean = function(){
for(var i=0; i < this.dirty.length; i++)
this.dirty[i].draw();
this.dirty = [];
}
this.over = function(ex,ey){
ex = ex - this.x;
ey = ey - this.y;
for(var i=0; i < this.sq.length; i++) {
if(this.sq[i].eleAtPoint(ex,ey)){
this.clean(); // clean up
this.dirty.push(this.sq[i]);
this.sq[i].over();
break;
}
}
}
this.init();
this.draw();
}
function square(x,y, ctx){
this.ctx = ctx;
this.x = x;
this.y = y;
this.h = 50;
this.w = 50;
this.draw = function(){
this.ctx.strokeStyle = "#eee";
this.ctx.strokeRect(this.x, this.y, this.w, this.w);
this.ctx.fillStyle = "#fff";
this.ctx.fillRect(this.x, this.y, this.w, this.w);
}
this.over = function() {
this.ctx.fillStyle = "red";
this.ctx.fillRect(this.x, this.y, this.w, this.w);
}
this.eleAtPoint = function(ex,ey){
if(ex < this.x + this.w && ex > this.x
&& ey > this.y && ey < this.y + this.h)
return true;
return false;
}
}
function over(){
var e = window.event;
grid.over(e.clientX ,e.clientY);
}
prepareCanvasGrid();
//-->
</script>
Updated code for better performance
Just to add to hungryMind's answer, if you don't want any boxes to remain highlighted when the mouse is no longer over the canvas, add these two things:
1) An else if
this.over = function(ex,ey){
ex = ex - this.x;
ey = ey - this.y;
for(var i=0; i < this.sq.length; i++) {
if(this.sq[i].eleAtPoint(ex,ey)){
this.clean(); // clean up
this.dirty.push(this.sq[i]);
this.sq[i].over();
break;
} else if (!this.sq[i].eleAtPoint(ex,ey)) {
this.sq[i].off();
}
}
}
2) A square off() method:
this.off = function() {
this.draw();
}

Categories

Resources