Image puzzle game - javascript

Edited to include entire code I found this cool image puzzle creator at [here][1] but I can't figure out how to adapt it so that upon clicking a "New Puzzle button" it changes the image to start a new puzzle? My first thought was creating an array??? Not sure, still very new to JS. Any help is appreciated.
window.onload = onReady;
var can;
var ctx;
var img;
var clickX;
var clickY;
var selected1;
var selected2;
var blockSize = 160;
var piecesArray = new Array();
function onReady()
{
can = document.getElementById('myCanvas');
if(navigator.userAgent.toLowerCase().indexOf('firefox') >= 0 || !can.getContext)
{
can.style.display = 'none';
document.getElementById('sorry').style.display = 'inline';
return;
}
ctx = can.getContext('2d');
img = new Image();
img.onload = onImage1Load;
img.src = "cat.jpg";
}
function onImage1Load()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = new Rectangle(i * blockSize, j * blockSize, i*blockSize + blockSize, j * blockSize + blockSize);
piecesArray.push(r);
}
}
scrambleArray(piecesArray, 30);
drawImage();
}
function Rectangle(left, top, right, bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
this.width = right - left;
this.height = bottom - top;
}
function scrambleArray(ar, times)
{
var count = 0;
var temp;
var index1;
var index2;
while(count < times)
{
index1 = Math.floor(Math.random()*piecesArray.length);
index2 = Math.floor(Math.random()*piecesArray.length);
temp = piecesArray[index1];
piecesArray[index1] = piecesArray[index2];
piecesArray[index2] = temp;
count++;
}
}
function drawImage()
{
var r;
for(var i = 0; i < 4; i++)
{
for(var j = 0; j < 3; j++)
{
r = piecesArray[i*3+j];
ctx.drawImage(img, r.left, r.top, r.width, r.height, i*blockSize, j*blockSize, blockSize, blockSize);
}
}
}
function highlightRect(drawX, drawY)
{
ctx.beginPath();
ctx.moveTo(drawX, drawY);
ctx.lineTo(drawX + blockSize, drawY);
ctx.lineTo(drawX + blockSize, drawY + blockSize);
ctx.lineTo(drawX, drawY + blockSize);
ctx.lineTo(drawX, drawY);
ctx.lineWidth = 2;
// set line color
ctx.strokeStyle = "#ff0000";
ctx.stroke();
}
function swapRects(r1, r2)
{
var index1;
var index2;
var temp = r1;
index1 = piecesArray.indexOf(r1);
index2 = piecesArray.indexOf(r2);
piecesArray[index1] = r2;
piecesArray[index2] = temp;
}
function onCanvasClick(evt)
{
clickX = evt.offsetX;
clickY = evt.offsetY;
var drawX = Math.floor(clickX / blockSize);
var drawY = Math.floor(clickY / blockSize);
var index = drawX * 3 + drawY;
var targetRect = piecesArray[index];
var drawHighlight = true;
drawX *= blockSize;
drawY *= blockSize;
ctx.clearRect(0, 0, 640, 480);
if(selected1 != undefined && selected2 != undefined)
{
selected1 = selected2 = undefined;
}
if(selected1 == undefined)
{
selected1 = targetRect;
}
else
{
selected2 = targetRect;
swapRects(selected1, selected2);
drawHighlight = false;
}
drawImage();
if(drawHighlight)
highlightRect(drawX, drawY);
}
<html>
<head>
<title>HTML5 Puzzle Game</title>
<script type="text/javascript">
</script>
</head>
<body style="background-color:#fbfbfb;" >
<div style="margin:0 auto; width:640px; height:480px; border: 4px solid #cc6699;">
<img id="sorry" src="sorry.jpg" style="display:none;"/>
<canvas id="myCanvas" width="640" height="480" onclick="onCanvasClick(event);">
</canvas>
</div>
</body>
</html>

1) Remove This from if condition block navigator.userAgent.toLowerCase().indexOf('firefox') >= 0, It got stucked on firefox. So no need to write this in if condition.
2) As you want a button "New Puzzle button" to replace new image
<button id="some id here">New Puzzle button</button> put this in html below the canvas(or wherever you want).
bind CLICK event on button using button's ID document.getElementById("some ID here").onclick = somefunction(){ onReady() };
As you see above the onReady() inside of button onclick function.
Now final thing use Array of images and use math.random or for loop inside of onReady function before img.src and assign the value like imagearray[somenumber here].

Related

How can I make a canvas element responsive when resizing the screen?

I have Matrix canvas on my site and there is problem with responsiveness when I change the width of the viewport the canvas doesn't update to fit.
https://codepen.io/ems-sin/pen/zYjpree
HTML
<canvas id="bglitch" ></canvas>
CSS
*{
margin:0;
background-color:#010b13;
overflow: hidden;
}
#bglitch{
opacity: 0.5;
z-index: -10;
top: 0;
right:0;
}
Javascript
var bglitch = document.getElementById("bglitch");
var ctx = bglitch.getContext("2d");
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var matrix = "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ";
matrix = matrix.split("");
var font_size = 24;
var columns = bglitch.width/font_size;
var drops = [];
for(var x = 0; x < columns; x++)
drops[x] = 1;
function draw()
{
ctx.fillStyle = "rgba(0, 0, 0, 0.04)";
ctx.fillRect(0, 0, bglitch.width, bglitch.height);
ctx.fillStyle = "#f4427d";
ctx.font = font_size + "px arial";
for(var i = 0; i < drops.length; i++){
var text = matrix[Math.floor(Math.random()*matrix.length)];
ctx.fillText(text, i*font_size, drops[i]*font_size);
if(drops[i]*font_size > bglitch.height && Math.random() > 0.975)
drops[i] = 0;
drops[i]++;
}
}
setInterval(draw, 35);
You need to make your code into a function which gets called on the resize event so that the dimensions are updated.
This snippet also clears the current timing interval (if there is one) before starting another one.
<style>
<canvas id="bglitch"></canvas>
</style>
<canvas id="bglitch"></canvas>
<script>
var bglitch = document.getElementById("bglitch");
var ctx = bglitch.getContext("2d");
let timer = '';
function init() {
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var matrix = "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ";
matrix = matrix.split("");
var font_size = 24;
var columns = bglitch.width / font_size;
var drops = [];
for (var x = 0; x < columns; x++)
drops[x] = 1;
function draw() {
ctx.fillStyle = "rgba(0, 0, 0, 0.04)";
ctx.fillRect(0, 0, bglitch.width, bglitch.height);
ctx.fillStyle = "#f4427d";
ctx.font = font_size + "px arial";
for (var i = 0; i < drops.length; i++) {
var text = matrix[Math.floor(Math.random() * matrix.length)];
ctx.fillText(text, i * font_size, drops[i] * font_size);
if (drops[i] * font_size > bglitch.height && Math.random() > 0.975)
drops[i] = 0;
drops[i]++;
}
}
clearInterval(timer);
timer = setInterval(draw, 35);
}
window.onresize = init;
window.onload = init;
</script>
You need to add resize event listener and recalculate columns accordingly.
Add this at the end of your javascript
window.addEventListener('resize', () => {
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var columns = bglitch.width/font_size;
for(var x = 0; x < columns; x++) drops[x] = 1;
})
Full working resize
var bglitch = document.getElementById("bglitch");
var ctx = bglitch.getContext("2d");
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var matrix = "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ";
matrix = matrix.split("");
var font_size = 24;
var columns = bglitch.width/font_size;
var drops = [];
for(var x = 0; x < columns; x++)
drops[x] = 1;
function draw()
{
ctx.fillStyle = "rgba(0, 0, 0, 0.04)";
ctx.fillRect(0, 0, bglitch.width, bglitch.height);
ctx.fillStyle = "#f4427d";
ctx.font = font_size + "px arial";
for(var i = 0; i < drops.length; i++){
var text = matrix[Math.floor(Math.random()*matrix.length)];
ctx.fillText(text, i*font_size, drops[i]*font_size);
if(drops[i]*font_size > bglitch.height && Math.random() > 0.975)
drops[i] = 0;
drops[i]++;
}
}
setInterval(draw, 35);
window.addEventListener('resize', () => {
bglitch.height = window.innerHeight;
bglitch.width = window.innerWidth;
var columns = bglitch.width/font_size;
for(var x = 0; x < columns; x++) drops[x] = 1;
})
*{
margin:0;
background-color:#010b13;
overflow: hidden;
}
#bglitch{
opacity: 0.5;
z-index: -10;
top: 0;
right:0;
}
<canvas id="bglitch" ></canvas>
It's better practice to separate your code into functions. For example init() function that sets all initial variables and run function that will run setTimeout and so on.
let bgData = {
element: undefined,
g: undefined,
matrix: "アィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽ".split(''),
fontSize: 24,
columns: undefined,
drops: [],
};
function init() {
bgData.element = document.getElementById("bglitch");
bgData.g = bgData.element.getContext("2d");
resize();
window.addEventListener('resize', resize)
}
function resize() {
bgData.element.height = window.innerHeight;
bgData.element.width = window.innerWidth;
bgData.columns = bgData.element.width / bgData.fontSize;
for(let x = 0; x < bgData.columns; x++) bgData.drops[x] = 1;
}
function draw() {
bgData.g.fillStyle = "rgba(0, 0, 0, 0.04)";
bgData.g.fillRect(0, 0, bgData.element.width, bgData.element.height);
bgData.g.fillStyle = "#f4427d";
bgData.g.font = bgData.fontSize + "px arial";
for(let i = 0; i < bgData.drops.length; i++) {
const text = bgData.matrix[Math.floor(Math.random()*bgData.matrix.length)];
bgData.g.fillText(text, i * bgData.fontSize, bgData.drops[i] * bgData.fontSize);
if(bgData.drops[i] * bgData.fontSize > bgData.element.height && Math.random() > 0.975) bgData.drops[i] = 0;
bgData.drops[i]++;
}
}
let interval;
function stop() {
clearInterval(interval);
window.removeEventListener('resize', resize)
}
function run() {
stop();
init();
interval = setInterval(draw, 35);
}
run();
*{
margin:0;
background-color:#010b13;
overflow: hidden;
}
#bglitch{
opacity: 0.5;
z-index: -10;
top: 0;
right:0;
}
<canvas id="bglitch" ></canvas>

How to generate continues Colorful Artistic Perlin Flow Field

I am trying to achieve effect as shown in the picture below:
Im using p5.js library but im not a graphics programmer and thats why its very difficult to achieve this particular graphical effect. I am sharing my code with you and also I followed this tutorial.
Index.html
<html>
<head>
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.min.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="particle.js"></script>
</head>
<body>
</body>
</html>
particle.js
function Particle() {
this.pos = createVector(random(width), random(height));
this.vel = createVector(0, 0);
this.acc = createVector(0, 0);
this.maxspeed = 4;
this.h = 0;
this.alphaPower = 20;
this.prevPos = this.pos.copy();
this.update = function() {
this.vel.add(this.acc);
this.vel.limit(this.maxspeed);
this.pos.add(this.vel);
this.acc.mult(0);
}
this.follow = function(vectors) {
var x = floor(this.pos.x / scl);
var y = floor(this.pos.y / scl);
var index = x + y * cols;
var force = vectors[index];
this.applyForce(force);
}
this.applyForce = function(force) {
this.acc.add(force);
}
this.showBlue = function() {
stroke(0, 76, 153, this.alphaPower);
strokeWeight(1);
line(this.pos.x, this.pos.y, this.prevPos.x, this.prevPos.y);
this.updatePrev();
}
this.showMaroon = function() {
stroke(165, 0, 68, this.alphaPower); // maroon
strokeWeight(1);
line(this.pos.x, this.pos.y, this.prevPos.x, this.prevPos.y);
this.updatePrev();
}
this.showYellow = function() {
stroke(237, 188, 0, this.alphaPower);
//stroke(1,2);
strokeWeight(1);
line(this.pos.x, this.pos.y, this.prevPos.x, this.prevPos.y);
this.updatePrev();
}
this.updatePrev = function() {
this.prevPos.x = this.pos.x;
this.prevPos.y = this.pos.y;
}
this.edges = function() {
if (this.pos.x > width) {
this.pos.x = 0;
this.updatePrev();
}
if (this.pos.x < 0) {
this.pos.x = width;
this.updatePrev();
}
if (this.pos.y > height) {
this.pos.y = 0;
this.updatePrev();
}
if (this.pos.y < 0) {
this.pos.y = height;
this.updatePrev();
}
}
}
sketch.js
var inc = 0.01;
var scl = 10;
var cols, rows;
var zoff = 0;
var fr;
var particles = [];
var particlesMaroon = [];
var particlesBlue = [];
var particlesYellow = [];
var flowfield;
var flowfieldMaroon;
var flowfieldBlue;
var flowfieldYellow;
var gamma_is_high = false;
var beta_is_high = false;
var alpha_is_high = false;
var maroon_data=1000;
var blue_data = 1000;
var yellow_data = 1000;
setInterval(function() {
ChangeLines();
}, 5000);
function dataRequest(){
socket.emit('datarequest', {data: "request"});
}
function ChangeLines(){
maroon_data = random(500, 2000);
blue_data = random(500, 2000);
yellow_data = random(500, 2000);
gamma_is_high = true;
alpha_is_high = true;
beta_is_high = true;
}
function setup() {
slider = createSlider(0.01, 0.1, 0.02,0);
slider.position(10, 10);
slider.style('width', '80px');
ChangeLines();
createCanvas(windowWidth-15, windowHeight-20);
cols = floor(width / scl);
rows = floor(height / scl);
fr = createP('');
flowfield = new Array(cols * rows);
flowfieldMaroon = new Array(cols * rows);
flowfieldBlue = new Array(cols * rows);
flowfieldYellow = new Array(cols * rows);
for (var i = 0; i < 1000; i++) {
particles[i] = new Particle();
particlesMaroon[i] = new Particle();
particlesBlue[i] = new Particle();
particlesYellow[i] = new Particle();
}
background(255);
}
function draw() {
let val = slider.value();
inc = val;
var yoff = 0;
for (var y = 0; y < rows; y++) {
var xoff = 0;
for (var x = 0; x < cols; x++) {
var index = x + y * cols;
var angle = noise(xoff, yoff, zoff) * TWO_PI;
var angleMaroon = noise(xoff, yoff, zoff) * TWO_PI;
var angleBlue = noise(xoff, yoff, zoff) * TWO_PI;
var angleYellow = noise(xoff, yoff, zoff) * TWO_PI;
var v = p5.Vector.fromAngle(angle);
var vm = p5.Vector.fromAngle(angleMaroon);
var vb = p5.Vector.fromAngle(angleBlue);
var vy = p5.Vector.fromAngle(angleYellow);
v.setMag(5);
vm.setMag(5);
vb.setMag(5);
vy.setMag(5);
flowfield[index] = v;
flowfieldMaroon[index] = vm;
flowfieldBlue[index] = vb;
flowfieldYellow[index] = vy;
xoff += inc;
}
yoff += inc;
}
zoff += 0.0003;
for (var i = 0; i < particles.length; i++) {
if(gamma_is_high==true){
particlesMaroon[i].follow(flowfieldMaroon);
particlesMaroon[i].update();
particlesMaroon[i].edges();
particlesMaroon[i].showMaroon();
}
if(beta_is_high){
particlesBlue[i].follow(flowfieldBlue);
particlesBlue[i].update();
particlesBlue[i].edges();
particlesBlue[i].showBlue();
}
if(alpha_is_high){
particlesYellow[i].follow(flowfieldYellow);
particlesYellow[i].update();
particlesYellow[i].edges();
particlesYellow[i].showYellow();
}
}
fr.html(floor(frameRate()));
}
The variables maroon_data, blue_dataand yellow_data are data coming from EEG device which will be calculated later but for now its hard coded values for prototype only. Also booleans gamma_is_high, beta_is_high and alpha_is_high are set to true for now. But with this much effort I only manage to achieve this as shown below:
And the actual output is like this:
Kindly help me get this actual output. Any help would be appreciated. Thanks.
Ive sorta done this before. I only had one array of particles and just changed their rgb values by a small random amount. I used an object to store the colour values.
function setup() {
//Do all the normal stuff
var c = {r: 100, g:100, b:100)
}
function draw() {
//All the other stuff
c.r += random(-3,3);
c.g += random(-3,3);
c.b += random(-3,3);
}
And then in the particle:
show() {
fill(c.r,c.g,c.b, whateverAlphaYouWant);
//Do all the rest
}
You can always tweak the values to get whatever colour you want.

Code crashes because object's .rad property becomes undefined

I am creating an ecosystem with my code consisting of plants, herbivores, and carnivores being represented through circles. For some reason, my code has been crashing after a certain amount of time ranging from 30 seconds to 8 minutes but no more than that.
After doing some digging I have found out that the crash is a result of my object's .rad property becoming undefined for some reason. It's probably a result of me improperly setting up my functions but I haven't been able to find a solution.
var plantSpawn = 5;
var herbSpawn = 3;
var carnSpawn = 2;
var myPlants = new Array();
var myCarns = new Array();
var myHerbs = new Array();
//////////////PLANTS//////////////////
function createPlants() {
reproducePlants();
setInterval(reproducePlants, 5000);
}
function reproducePlants() {
for(var p=0; p<plantSpawn; p++){
var rr = Math.round(Math.random() * 150);
var gg = Math.round(Math.random() * 255);
var bb = Math.round(Math.random() * 150);
var plant = new Object();
plant.x = Math.random() * canvas.width;
plant.y = Math.random() * canvas.height;
plant.rad = 2 + Math.random()*2;
plant.skin = 'rgba('+rr+','+gg+','+bb+', 1)';
myPlants.push(plant);
}
}
function drawPlants(){
var plantAmt = myPlants.length;
for(var j=0; j<plantAmt; j++) {
if (myPlants[j].x + myPlants[j].rad >= canvas.width) {
myPlants[j].x -= 10;
}
if (myPlants[j].y + myPlants[j].rad >= canvas.height) {
myPlants[j].y -= 10;
}
context.beginPath();
context.arc(myPlants[j].x, myPlants[j].y, myPlants[j].rad, 0, Math.PI*2, false);
context.closePath();
context.fillStyle = myPlants[j].skin;
context.fill();
}
}
function killPlants() {
plantDeath();
setInterval(plantDeath, 30000); //play with inc
}
function plantDeath() {
myPlants.splice(0,5);
}
//////////////HERBS//////////////////
function herbsLife(){
reproduceHerbs();
setInterval(reproduceHerbs, 10000);
herbsDeath();
setInterval(herbsDeath, 90000); //1.5 minutes
setInterval(herbsStarve, 10000); //10 seconds
}
function reproduceHerbs() {
for (var h=0; h<herbSpawn; h++){
var gg = Math.round(Math.random() * 100);
var bb = Math.round(Math.random() * 255);
var herbivore = new Object();
herbivore.x = Math.random() * canvas.width;
herbivore.y = Math.random() * canvas.height;
herbivore.rad = 5 + Math.random()*3;
herbivore.skin = 'rgba(0,'+gg+','+bb+', 1)';
herbivore.speedH = -3 + Math.random()*1.2;
herbivore.speedV = -3 + Math.random()*1.2;
herbivore.dirH = 1;
herbivore.dirV = 1;
myHerbs.push(herbivore);
}
}
function drawHerbs() {
var herbAmt = myHerbs.length;
for(var j=0; j<herbAmt; j++) {
var hX = myHerbs[j].x;
var hY = myHerbs[j].y;
//HERB MOVEMENT//
myHerbs[j].x += myHerbs[j].dirH * myHerbs[j].speedH;
if (myHerbs[j].x > canvas.width + myHerbs[j].rad || myHerbs[j].x < 0){
myHerbs[j].dirH *= -1;
}
myHerbs[j].y += myHerbs[j].dirV * myHerbs[j].speedV;
if (myHerbs[j].y > canvas.height + myHerbs[j].rad || myHerbs[j].y < 0){
myHerbs[j].dirV *= -1;
}
context.beginPath();
context.arc(myHerbs[j].x, myHerbs[j].y, myHerbs[j].rad, 0, Math.PI*2, false);
context.closePath();
context.fillStyle = myHerbs[j].skin;
context.fill();
}
}
function herbsDeath() {
myHerbs.splice(0,3);
}
function herbsEat() {
for (var k=0; k<myPlants.length; k++){
var pX = myPlants[k].x;
var pY = myPlants[k].y;
for (var h=0; h<myHerbs.length; h++){
var hX = myHerbs[h].x;
var hY = myHerbs[h].y;
var eX = hX - pX;
var eY = hY - pY;
var dist = Math.sqrt(Math.pow(eX,2) + Math.pow(eY,2));
if (dist < myPlants[k].rad*2) {
myPlants.splice(k,1);
myHerbs[h].rad += 1;
}
}
}
}
function herbsStarve() {
for (var s=0; s<myPlants.length; s++){
myHerbs[s].rad -= 1;
if (myHerbs[s].rad <= 2) {
myHerbs.splice(s,1);
}
}
}
//////////////CARNS//////////////////
function carnsLife() {
reproduceCarns();
setInterval(reproduceCarns, 20000); //20 seconds
carnsDeath();
setInterval(carnsDeath, 60000); //50 seconds
setInterval(carnsStarve, 7500); //10 seconds
}
function reproduceCarns() {
for (var c=0; c<carnSpawn; c++){
var rr = Math.round(Math.random() * 255);
var gg = Math.round(Math.random() * 100);
var carnivore = new Object();
carnivore.x = Math.random() * canvas.width;
carnivore.y = Math.random() * canvas.height;
carnivore.rad = 7 + Math.random()*3;
carnivore.skin = 'rgba('+rr+','+gg+',0, 1)';
//bigger random = slower//
carnivore.speedH = -3 + Math.random()*2;
carnivore.speedV = -3 + Math.random()*2;
carnivore.dirH = 1;
carnivore.dirV = 1;
myCarns.push(carnivore);
}
}
function drawCarns() {
var carnAmt = myCarns.length;
for(var j=0; j<carnAmt; j++) {
//CARN MOVEMENT//
myCarns[j].x += myCarns[j].dirH * myCarns[j].speedH;
if (myCarns[j].x > canvas.width + myCarns[j].rad || myCarns[j].x < 0){
myCarns[j].dirH *= -1;
}
myCarns[j].y += myCarns[j].dirV * myCarns[j].speedV;
if (myCarns[j].y > canvas.height + myCarns[j].rad || myCarns[j].y < 0){
myCarns[j].dirV *= -1;
}
context.beginPath();
context.arc(myCarns[j].x, myCarns[j].y, myCarns[j].rad, 0, Math.PI*2, false);
context.closePath();
context.fillStyle = myCarns[j].skin;
context.fill();
}
}
function carnsDeath() {
myCarns.splice(0,2);
}
function carnsEat() {
for (var k=0; k<myCarns.length; k++){
var cX = myCarns[k].x;
var cY = myCarns[k].y;
for (var h=0; h<myHerbs.length; h++){
var hX = myHerbs[h].x;
var hY = myHerbs[h].y;
var eX = cX - hX;
var eY = cY - hY;
var dist = Math.sqrt(Math.pow(eX,2) + Math.pow(eY,2));
if (dist < myCarns[k].rad*1.2 && myCarns[k].rad > myHerbs[h].rad) {
myHerbs.splice(h,1);
myCarns[k].rad += 1;
}
}
}
}
function carnsStarve() {
for (var q=0; q<myPlants.length; q++){
myCarns[q].rad = myCarns[q].rad - 1;
if (myCarns[q].rad <= 5) {
myCarns.splice(q,1);
}
}
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title> Ecosystem </title>
<!-- import external .js scripts here -->
<script type="text/javascript" src="Creatures.js" ></script>
<!-- modify CSS properties here -->
<style type="text/css">
body,td,th {
font-family: Monaco, "Courier New", "monospace";
font-size: 14px;
color: rgba(255,255,255,1);
}
body {
background-color: rgba(0,0,0,1);
}
#container {
position: relative;
text-align: left;
width: 95%;
height: 800px;
}
#fmxCanvas {
position: relative;
background-color:rgba(255,255,255,1);
border: rgba(255,255,255,1) thin dashed;
cursor: crosshair;
display: inline-block;
}
</style>
</head>
<body>
<div id="container">
<!-- START HTML CODE HERE -->
<canvas id="fmxCanvas" width="800" height="800"></canvas>
<div id="display"></div>
<!-- FINISH HTML CODE HERE -->
</div>
<script>
///////////////////////////////////////////////////////////////////////
// DECLARE requestAnimFrame
var rAF = window.requestAnimFrame ||
window.mozRequestAnimFrame ||
window.webkitRequestAnimFrame ||
window.msRequestAnimFrame;
var fps = 30;
window.requestAnimFrame = (
function(callback) {
return rAF ||
function(callback) {
window.setTimeout(callback, 1000 / fps);
};
})();
///////////////////////////////////////////////////////////////////////
// DEFINE GLOBAL VARIABLES HERE
var canvas;
var context;
canvas = document.getElementById("fmxCanvas");
context = canvas.getContext("2d");
var canvas1;
var context1;
canvas1 = document.createElement("canvas");
context1 = canvas1.getContext("2d");
canvas1.width = canvas.width;
canvas1.height = canvas.height;
var display;
display = document.getElementById('display');
var counter;
///////////////////////////////////////////////////////////////////////
// DEFINE YOUR GLOBAL VARIABLES HERE
///////////////////////////////////////////////////////////////////////
// CALL THE EVENT LISTENERS
window.addEventListener("load", setup, false);
//////////////////////////////////////////////////////////////////////
// ADD EVENT LISTENERS
canvas.addEventListener("mousemove", mousePos, false);
//////////////////////////////////////////////////////////////////////
// MOUSE COORDINATES
var stage, mouseX, mouseY;
function mousePos(event) {
stage = canvas.getBoundingClientRect();
mouseX = event.clientX - stage.left;
mouseY = event.clientY - stage.top;
}
/////////////////////////////////////////////////////////////////////
// INITIALIZE THE STARTING FUNCTION
function setup() {
/////////////////////////////////////////////////////////////////////
// DECLARE STARTING VALUES OF GLOBAL VARIABLES
counter = 0;
mouseX = canvas.width/2;
mouseY = canvas.height/2;
/////////////////////////////////////////////////////////////////////
// CALL SUBSEQUENT FUNCTIONS, as many as you need
createPlants();
killPlants();
herbsLife();
carnsLife();
clear(); // COVER TRANSPARENT CANVAS OR CLEAR CANVAS
draw(); // THIS IS WHERE EVERYTHING HAPPENS
}
////////////////////////////////////////////////////////////////////
// CLEAR THE CANVAS FOR ANIMATION
// USE THIS AREA TO MODIFY BKGD
function clear() {
context.clearRect(0,0,canvas.width, canvas.height);
context1.clearRect(0,0,canvas.width, canvas.height);
// clear additional contexts here if you have more than canvas1
}
////////////////////////////////////////////////////////////////////
// THIS IS WHERE EVERYTHING HAPPENS
function draw() {
counter += 0.1; // EASIER FOR SINE COSINE FUNCTIONS
//if (counter > Math.PI*200) { counter = 0; } // RESET COUNTER
clear(); // USE THIS TO REFRESH THE FRAME AND CLEAR CANVAS
////////////////////////////////////////////////////////////////////
// >>>START HERE>>>START HERE>>>START HERE>>>START HERE>>>START HERE
drawPlants();
drawHerbs();
drawCarns();
herbsEat();
carnsEat();
// <<<END HERE<<<END HERE<<<END HERE<<<END HERE<<<END HERE<<<END HERE
///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// HTML DISPLAY FIELD FOR TESTING PURPOSES
display.innerHTML =
// mouseX + " || " + mouseY +
" || Minutes = " + Math.trunc(counter/180) +
" || Seconds = " + Math.round(counter/3) +
"<br><br>" +
"Plants = " + myPlants.length +
"<br>" +
"Herbivores = " + myHerbs.length +
"<br>" +
"Carnivores = " + myCarns.length;
/////////////////////////////////////////////////////////////////
// LAST LINE CREATES THE ANIMATION
requestAnimFrame(draw); // CALLS draw() every nth of a second
}
</script>
</body>
</html>

Keep track and display arrival order of array elements after animation ends in JavaScript

So, I have created an array of 10 blocks(rectangles) that move horizontally towards a "finish" line (end of canvas width) with variable speeds. I'm looking for a way to keep track of the arrival order of each array element and display it on top of each rectangle as it stops moving. I've tried using a counter and the fillText method to do that, but it only works until other elements come to a full stop and then it replaces the order. For a better view of what happens, here is my code. If anyone has any suggestions on what to use in order to fulfill my goal, it is very much appreciated. Keep in mind that I only use plain JavaScript as in no jQuery or other frameworks as I am learning the basics. Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cars</title>
<style>
canvas {
border:1px solid #3D0404;
}
h2 {
margin-left:23%;
}
</style>
<script>
var c;
var ctx;
var cars = [];
var width = 100;
var height = 100;
var x = 0;
var y = 0;
var i;
var temp;
var cw = 1000;
var ch = 1000;
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function init() {
c = document.getElementById("myCanvas");
ctx = c.getContext("2d");
pushCar();
}
function CreateCar(x,y,width,height,speed){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.speed = speed;
}
function pushCar(){
for (var i=0; i<10; i++){
var speed = Math.random() * 10;
var car = new CreateCar(x,y,width,height,speed);
cars.push(car);
y += 100;
}
drawAll();
}
function clear (){
ctx.clearRect (0,0,cw,ch);
}
function draw(cars){
ctx.beginPath();
ctx.fillStyle = "#f00";
ctx.fillRect(temp.x, temp.y, width, height);
ctx.strokeStyle = "#000";
ctx.outlineWidth = 2;
ctx.strokeRect(temp.x, temp.y, width, height);
ctx.closePath();
}
function drawAll(){
clear();
var z = 1;
for (var i=0; i<cars.length; i++){
temp = cars[i];
draw(temp);
if (temp.x+100 < c.width){
temp.x += temp.speed;
}else {
ctx.font = "20pt Verdana";
ctx.fillStyle = "#000";
ctx.fillText(z, 950, temp.y+55);
z++;
}
}
requestAnimFrame(drawAll, c);
}
</script>
</head>
<body onLoad = "init()">
<canvas id="myCanvas" width="1000" height="1000"></canvas>
</body>
</html>
You need to put the z variable outside the loop, and save the position of each car in an object. You also need to check if position[i] is already defined to avoid incrementing the current position more times than needed.
var z;
var position;
function drawAll() {
clear();
for (var i = 0; i < cars.length; i++) {
temp = cars[i];
draw(temp);
if (temp.x + 100 < c.width) {
temp.x += temp.speed;
} else {
if (!position[i]) {
position[i] = z;
z++;
}
ctx.font = "20pt Verdana";
ctx.fillStyle = "#000";
ctx.fillText(position[i], 950, temp.y + 55);
}
}
requestAnimFrame(drawAll, c);
}
http://jsfiddle.net/acasaccia/u2vhaqyt/

How to make the objects fall in javascript?

I am trying to make this game, you should not collide the falling object. I have the objects falling and I have my black square, but it flashes when I run it and Im not sure how to make the code stop when the two objects collide together.
here is the code that I have so far!
<html>
<body>
<canvas id="canvasRegn" width="600" height="450"style="margin:100px;"></canvas>
<script>
var ctx;
var imgBg;
var imgDrops;
var noOfDrops = 50;
var fallingDrops = [];
function drawBackground(){
ctx.drawImage(imgBg, 0, 0); //Background
}
function draw() {
drawBackground();
for (var i=0; i< noOfDrops; i++)
{
ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop
fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed
if (fallingDrops[i].y > 480) { //Repeat the raindrop when it falls out of view
fallingDrops[i].y = -25 //Account for the image size
fallingDrops[i].x = Math.random() * 800; //Make it appear randomly along the width
}
}
}
function setup() {
var canvas = document.getElementById('canvasRegn');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
imgBg = new Image();
imgBg.src = "http://www.hamdancommunications.com/HComm/img/wite%20square.png";
setInterval(draw, 36);
for (var i = 0; i < noOfDrops; i++) {
var fallingDr = new Object();
fallingDr["image"] = new Image();
fallingDr.image.src = 'http://s18.postimg.org/o6jpmdf9x/Line1.jpg';
fallingDr["x"] = Math.random() * 800;
fallingDr["y"] = Math.random() * 5;
fallingDr["speed"] = 3 + Math.random() * 5;
fallingDrops.push(fallingDr);
anotherGame();
}
}
}
setup();
function anotherGame(){
var canvas = document.getElementById("canvasRegn");
var ctx = canvas.getContext('2d');
canvas.addEventListener("mousedown", clicked);
canvas.addEventListener("mousemove", moved);
canvas.addEventListener("mouseup", released);
var isclicked = 0;
var square = new Object();
square.color = "black";
square.x = 100;
square.y = 100;
square.w = 50;
square.h = 50;
var offX = 0;
var offY = 0;
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = square.color;
ctx.fillRect(square.x,square.y,square.w,square.h);
}
function game(){
}
function clicked(e){
var x = e.offsetX;
var y = e.offsetY;
if(x >= square.x && x <= square.x + square.w &&
y >= square.y && y <= square.y + square.h){
isclicked = 1;
offX = x - square.x;
offY = y - square.y;
}
}
function moved(e){
if(isclicked == 1){
var x = e.offsetX;
var y = e.offsetY;
square.x = x - offX;
square.y = y - offY;
}
}
function released(e){
var x = e.offsetX;
var y = e.offsetY;
isclicked = 0;
}
var drawtimer = setInterval(draw, 1000/30);
var gametimer = setInterval(game, 1000/10);
}
</script>
</body>
</html>

Categories

Resources