How can I use round dots in my animated line in HTML5 canvas? - animation

I am using line creation on HTML5 canvas to create two animated dashed paths, one after the other. I simply want to change the dashes to rounded dots.
I've seen setting context lineCap ='round', etc but it doesn't work
var canvas;
var ctx;
var pathColor="black";
function Vector(x, y)
{
this.X = x;
this.Y = y;
}
var m1, c1;
var pCount1=0;
var pCount2=0;
var pathInt = null;
var points1 = [new Vector(1400, 1500),new Vector(1365, 1495),new Vector(1330, 1490),new Vector(1295, 1485),new Vector(1260, 1480)];
var points2 = [new Vector(1280, 480),new Vector(1195, 470),new Vector(1110, 460),new Vector(1080, 450),new Vector(1000, 240),new Vector(1300, 140),new Vector(1580, 140),new Vector(1590, 180),];
function getClr() {
if(pathColor=="lightgrey") {
pathColor="black";
}
else {
pathColor="lightgrey";
}
}
window.onload = function()
{
m1 = document.querySelector("#b");
c1 = m1.getContext("2d");
pathInt = setInterval(function(){ pathTo(); }, 250);
};
function pathTo()
{
if(pCount1 <= points1.length && points1.length!=0)
{
c1.strokeStyle = pathColor;
c1.lineWidth = 15;
c1.setLineDash([25, 10]);
c1.beginPath();
c1.moveTo(points1[0].X, points1[0].Y);
for(var i = 0; i < pCount1; i++)
{
c1.lineTo(points1[i].X, points1[i].Y);
}
pCount1++;
c1.stroke();
}
else if(pCount2 <= points2.length && points2.length!=0)
{
c1.strokeStyle = pathColor;
c1.lineWidth = 15;
c1.setLineDash([25, 10]);
c1.beginPath();
c1.moveTo(points2[0].X, points2[0].Y);
for(var i = 1; i < pCount2; i++)
{
c1.lineTo(points2[i].X, points2[i].Y);
}
pCount2++;
c1.stroke();
pCount2++;
}
else {
clearInterval(pathInt);
setTimeout(function(){ redoPath(); }, 5000);
}
}
function redoPath() {
pCount1=0;
pCount2=0;
//c1.clearRect(0, 0, m1.width, m1.height);
getClr();
pathInt = setInterval(function(){ pathTo(); }, 250);
}
<canvas id="b" width="1746" height="1746" style="position:absolute;top:100px;left:50px;z-index:100;">
</canvas>
I know this must be possible, ..but not sure which properties I need to change. Any help is appreciated.

Related

Need to upload user's image input - P5 JavaScript library

I have a Sketch in Processing written in P5.js, but I don't know how to implement user's input.
The program needs to get .jpg image and it's working on it.
Every my attempt of user-input implementation ends with blank screen or endless "Loading..." screen.
Below is example with preloaded image (I need user to do it).
let img;
let size;
let pixels = [];
function preload(){
img=loadImage('image.jpg');
}
function setup() {
img.resize(windowHeight,0);
size = img.height/2;
createCanvas(img.width, img.height);
background(0);
makePixels();
drawPortrait();
}
function makePixels(){
for(let y=0; y<height; y+=size){
for(let x=0; x<width; x+=size){
let c = img.get(x,y);
tint(c);
pixels.push ( new Pixel (x,y,size,c) );
}
}
}
function drawPortrait(){
for(let p of pixels){
p.show();
}
}
function drawLastFour(){
for(let i = pixels.length-4; i<pixels.length; i++){
pixels[i].show();
}
}
function mouseMoved(){
for(let i = 0; i<pixels.length; i++){
if( (mouseX > pixels[i].x) && (mouseX <= pixels[i].x+pixels[i].s) && (mouseY > pixels[i].y) && (mouseY <= pixels[i].y+pixels[i].s) ){
for(let py = pixels[i].y; py<pixels[i].y+pixels[i].s; py+=pixels[i].s/2){
for(let px = pixels[i].x; px<pixels[i].x+pixels[i].s; px+=pixels[i].s/2){
let c = img.get(px, py);
pixels.push( new Pixel(px,py,pixels[i].s/2, c) );
}
}
pixels.splice(i,1);
break;
}
}
drawLastFour();
}
You can use the createFileInput function to create an input element of type file. Your user can then select an image file, which can be used by your sketch. Here is the (slightly modified) example code that shows how you can use it:
let inputElement;
let userImage;
function setup() {
inputElement = createFileInput(handleFile);
inputElement.position(0, 0);
}
function draw() {
background(255);
if (userImage != null) {
image(userImage, 0, 0, width, height);
}
}
function handleFile(file) {
print(file);
if (file.type === 'image') {
userImage = createImg(file.data, '');
userImage.hide();
} else {
userImage = null;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

Error: It looks like you're mixing "active" and "Static" modes in Processing

The code is an open processing program which I downloaded but doesn't seem to be working. I am a beginner and need help in understanding what to do with the error. Thanks in advance.
Please find the openprocessing code here: https://www.openprocessing.org/sketch/407405
void setup() {
size(400,400,0);
}
rectMode(CENTER);
textAlign(CENTER,CENTER);
var P=200;
var LOSE=false;
var score=0;
var particlestor = [];
var Timer=millis();
var fall = function(position) {
this.velocity = new PVector(0,3);
this.position = position.get();
fall.prototype.run = function() {
this.position.add(this.velocity);
noStroke();
fill(0, 0,0);
rect(this.position.x, this.position.y, 20, 20);
if(dist(this.position.x, this.position.y,P,390)<=20){LOSE=true;}};
fall.prototype.isDead = function() {
if (this.position.y > 400) {return true;} else {return false;}
};};
for(var i=0;i<=4;i++){particlestor.push(new fall(new PVector(random(0,400), random(-10,-600))));}
draw = function() {
if(LOSE===false){
background(255, 255, 255);
if(millis()-Timer>=1000){
Timer=millis();
score+=1;
particlestor.push(new fall(new PVector(random(0,400), random(-10,-400))));
}
P=mouseX;
for (var i = particlestor.length-1; i >= 0; i--) {
var p = particlestor[i];
p.run();
if (p.isDead()===true) {
particlestor.splice(i, 1);
particlestor.push(new fall(new PVector(random(0,400), random(-10,-400))));
}}
fill(240,0,0);
rect(P,390,20,20);
text(score,10,10);
if(P>400){LOSE=true;}
if(P<0){LOSE=true;}
}
if(LOSE===true){
textSize(60);
text("YOU LOSE\n score :"+score,200,200);
}};// 50 lines
The code above uses ProcessingJS. If you want to run the code locally on your machine you have a few options:
Have a look at the ProcessingJS QuickStart guides and use that
Port the code to Processing
Port the code to p5.js
For example:
var P=200;
var LOSE=false;
var score=0;
var particlestor = [];
var Timer;
function setup() {
createCanvas(400, 400, 0);
rectMode(CENTER);
textAlign(CENTER, CENTER);
Timer=millis();
for (var i=0; i<=4; i++) {
particlestor.push(new fall(createVector(random(0, 400), random(-10, -600))));
}
}
function draw() {
if (LOSE===false) {
background(255, 255, 255);
if (millis()-Timer>=1000) {
Timer=millis();
score+=1;
particlestor.push(new fall(createVector(random(0, 400), random(-10, -400))));
}
P=mouseX;
for (var i = particlestor.length-1; i >= 0; i--) {
var p = particlestor[i];
p.run();
if (p.isDead()===true) {
particlestor.splice(i, 1);
particlestor.push(new fall(createVector(random(0, 400), random(-10, -400))));
}
}
fill(240, 0, 0);
rect(P, 390, 20, 20);
text(score, 10, 10);
if (P>400) {
LOSE=true;
}
if (P<0) {
LOSE=true;
}
}
if (LOSE===true) {
textSize(60);
text("YOU LOSE\n score :"+score, 200, 200);
}
}
var fall = function(position) {
this.velocity = createVector(0, 3);
this.position = position.copy();
fall.prototype.run = function() {
this.position.add(this.velocity);
noStroke();
fill(0, 0, 0);
rect(this.position.x, this.position.y, 20, 20);
if (dist(this.position.x, this.position.y, P, 390)<=20) {
LOSE=true;
}
};
fall.prototype.isDead = function() {
if (this.position.y > 400) {
return true;
} else {
return false;
}
};
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.min.js"></script>
I recommend refactoring (cleaning the code, naming variables more meaningfully/consistent, commenting code sections, etc).
This would make it easy to understand the code and remix/adapt it to something better.

Three.js - can I detect geometry 'islands' when importing?

I'm importing .3DS models into Blender 2.72b, then exporting them with the Three.js import/export addon. The models have multiple geometry 'islands' (separate groups of connected faces and vertices), each with its own material. I'd like to be able to pair each material with its corresponding island, without having to create separate THREE.Geometry objects. After some digging, I found this question which suggests using a THREE.MeshFaceMaterial to achieve multiple materials for one object. The only problem is that the geometry in that example is a simple cube, whereas my models have hundreds of faces spread across 2-5 islands.
Does Three.js have functionality for identifying geometry 'islands' in a mesh?
No. three.js does not have functionality for identifying geometry 'islands' in a mesh.
When using MeshFaceMaterial, WebGLRenderer breaks the geometry into chunks anyway -- one chunk for each material. It does that because WebGL supports one shader per geometry.
I would not merge all your geometries, and then use MeshFaceMaterial, only to have the renderer break the single geometry apart.
You can merge geometries that share a single material if you wish.
three.js r.69
I tried with a function but still is not accurate, it produce more geometries than non connected geometries:
If somebody could have a look on it, it would be grate.
function groupGeometryIntoNonConnectedGeometries(geometry) {
const material = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
vertexColors: THREE.VertexColors
});
let geometryArray = [];
const indexArray = geometry.index.array;
const positionArray = geometry.attributes.position.array;
const positionCount = geometry.attributes.position.count;
const color = new THREE.Vector3(geometry.attributes.color.array[0], geometry.attributes.color.array[1], geometry.attributes.color.array[2]);
const totalTriangles = indexArray.length / 3;
let geometryCount = 0;
let indexValueAlreadyVisited = new Uint8Array(indexArray.length);
let structure = [];
/*
* indexValue: {
* child: [ [indexval0, indexval1], [] ],
* parent: null
* }
*/
// Initialize Structure:
for (var vextexIdx=0; vextexIdx<positionCount; vextexIdx++) {
structure[vextexIdx] = {
child: [],
parent: null
}
}
for (idx=0; idx<totalTriangles; idx++) {
const geoIndex1 = indexArray[idx*3];
const geoIndex2 = indexArray[idx*3+1];
const geoIndex3 = indexArray[idx*3+2];
const triangleIndexVertexArray = [ geoIndex1, geoIndex2, geoIndex3 ].sort(function(a, b) {
return a - b;
});
structure[ triangleIndexVertexArray[0] ].child.push(triangleIndexVertexArray[1], triangleIndexVertexArray[2]);
structure[ triangleIndexVertexArray[1] ].parent = triangleIndexVertexArray[0];
structure[ triangleIndexVertexArray[2] ].parent = triangleIndexVertexArray[0];
}
let count = 0;
let currentCount = 0;
let geometryStructureArray = [];
for (let strIdx=0; strIdx<structure.length; strIdx++) {
if (structure[strIdx].parent == null) {
currentCount = count;
geometryStructureArray[currentCount] = {
name: "G_" + currentCount,
indexMap: {},
currentIndex: 0,
indexArray: [],
positionArray: [],
colorArray: []
};
count += 1;
}
if (structure[strIdx].child.length > 0) {
const childLen = structure[strIdx].child.length / 2;
for (let childIdx=0; childIdx<childLen; childIdx++) {
const vertexIndex0 = strIdx;
const vertexIndex1 = structure[strIdx].child[childIdx*2];
const vertexIndex2 = structure[strIdx].child[childIdx*2+1];
const v0 = new THREE.Vector3( positionArray[strIdx*3], positionArray[strIdx*3+1], positionArray[strIdx*3+2] );
const v1 = new THREE.Vector3( positionArray[vertexIndex1*3], positionArray[vertexIndex1*3+1], positionArray[vertexIndex1*3+2] );
const v2 = new THREE.Vector3( positionArray[vertexIndex2*3], positionArray[vertexIndex2*3+1], positionArray[vertexIndex2*3+2] );
// check vertex0
if (geometryStructureArray[currentCount].indexMap[vertexIndex0] == undefined) {
geometryStructureArray[currentCount].indexMap[vertexIndex0] = geometryStructureArray[currentCount].currentIndex;
geometryStructureArray[currentCount].indexArray.push(geometryStructureArray[currentCount].currentIndex);
geometryStructureArray[currentCount].positionArray.push(v0.x, v0.y, v0.z);
geometryStructureArray[currentCount].colorArray.push(color.x, color.y, color.z);
geometryStructureArray[currentCount].currentIndex += 1;
} else {
geometryStructureArray[currentCount].indexArray.push(geometryStructureArray[currentCount].indexMap[vertexIndex0]);
}
// check vertex1
if (geometryStructureArray[currentCount].indexMap[vertexIndex1] == undefined) {
geometryStructureArray[currentCount].indexMap[vertexIndex1] = geometryStructureArray[currentCount].currentIndex;
geometryStructureArray[currentCount].indexArray.push(geometryStructureArray[currentCount].currentIndex);
geometryStructureArray[currentCount].positionArray.push(v1.x, v1.y, v1.z);
geometryStructureArray[currentCount].colorArray.push(color.x, color.y, color.z);
geometryStructureArray[currentCount].currentIndex += 1;
} else {
geometryStructureArray[currentCount].indexArray.push(geometryStructureArray[currentCount].indexMap[vertexIndex1]);
}
// check vertex1
if (geometryStructureArray[currentCount].indexMap[vertexIndex2] == undefined) {
geometryStructureArray[currentCount].indexMap[vertexIndex2] = geometryStructureArray[currentCount].currentIndex;
geometryStructureArray[currentCount].indexArray.push(geometryStructureArray[currentCount].currentIndex);
geometryStructureArray[currentCount].positionArray.push(v2.x, v2.y, v2.z);
geometryStructureArray[currentCount].colorArray.push(color.x, color.y, color.z);
geometryStructureArray[currentCount].currentIndex += 1;
} else {
geometryStructureArray[currentCount].indexArray.push(geometryStructureArray[currentCount].indexMap[vertexIndex2]);
}
}
}
}
// Convert to geometryArray:
const geometryStructureArrayLen = geometryStructureArray.length;
const object3d = new THREE.Object3D();
for (let geoIdx=0; geoIdx<geometryStructureArrayLen; geoIdx++) {
const geo = new THREE.BufferGeometry();
geo.name = "G_" + geoIdx;
const geoPositions = new Float32Array(geometryStructureArray[geoIdx].positionArray);
const geoColors = new Float32Array(geometryStructureArray[geoIdx].colorArray);
const geoIndices = new Uint32Array(geometryStructureArray[geoIdx].indexArray);
//console.log(geoIdx, "geoPositions: ", geoPositions);
//console.log(geoIdx, "geoColors: ", geoColors);
//console.log(geoIdx, "geoIndices: ", geoIndices);
geo.index = new THREE.BufferAttribute(geoIndices, 1, false);
geo.attributes.position = new THREE.BufferAttribute(geoPositions, 3, false);
geo.attributes.color = new THREE.BufferAttribute(geoColors, 3, true);
geo.computeBoundingSphere();
geo.computeBoundingBox();
const mesh = new THREE.Mesh(geo, material);
mesh.name = "M_" + geoIdx;
object3d.add(mesh);
}
//return [structure, geometryStructureArray, object3d, count];
return object3d;
}
Best regards
This is I think the correct way:
function unmergeGeometryArray(geometry) {
// Asumptions:
// geometry is BufferGeometry
// The geometry has no index duplicates (2 equal positions with different index) neither empty triangles, the geometry has been processed with mergeVertices function
// normal attribute is discarded, can be recomputed after, only color and position attributes are taken into account
const material = new THREE.MeshBasicMaterial({
side: THREE.DoubleSide,
vertexColors: THREE.VertexColors
});
const indexArray = geometry.index.array;
const positionArray = geometry.attributes.position.array;
const positionCount = geometry.attributes.position.count;
const totalTriangles = indexArray.length / 3;
let triangleVisitedArray = new Uint8Array(totalTriangles);
let indexVisitedArray = new Uint8Array(positionCount);
let indexToTriangleIndexMap = [];
let missingVertices = positionCount;
let missingTriangles = totalTriangles;
// Functions:
function computeTrianglesRecursive(index, out){
//console.log("- start of computeTriangles with index:", index);
if (indexVisitedArray[index] === 1 || missingVertices === 0 || missingTriangles === 0) {
return;
}
indexVisitedArray[index] = 1;
missingVertices -= 1;
let triangleIndexArray = indexToTriangleIndexMap[index];
for(let i=0; i<indexToTriangleIndexMap[index].length; i++) {
let triangleIndex = indexToTriangleIndexMap[index][i];
if (triangleVisitedArray[triangleIndex] === 0) {
triangleVisitedArray[triangleIndex] = 1
missingTriangles -= 1;
//console.log("-- index: ", index, "; i: ", i, "; triangleIndex: ", triangleIndex);
out.push(triangleIndex);
childIndex1 = indexArray[triangleIndex*3+1];
computeTriangles(childIndex1, out);
childIndex2 = indexArray[triangleIndex*3+2];
computeTriangles(childIndex2, out);
}
}
}
function computeTriangles(indexTocheck){
let out = [];
let startIndex = indexTocheck;
let indexToCheckArray = [indexTocheck];
let i = 0;
while (i<indexToCheckArray.length) {
let index = indexToCheckArray[i];
if (indexVisitedArray[index] == 0) {
indexVisitedArray[index] = 1;
missingVertices -= 1;
let triangleIndexArray = indexToTriangleIndexMap[index];
for(let j=0; j<indexToTriangleIndexMap[index].length; j++) {
let triangleIndex = indexToTriangleIndexMap[index][j];
if (triangleVisitedArray[triangleIndex] === 0) {
triangleVisitedArray[triangleIndex] = 1;
missingTriangles -= 1;
out.push(triangleIndex);
let rootIndex = indexArray[triangleIndex*3];
let child1Index = indexArray[triangleIndex*3+1];
let child2Index = indexArray[triangleIndex*3+2];
if (indexToCheckArray.indexOf(rootIndex) === -1) {
indexToCheckArray.push(rootIndex);
}
if (indexToCheckArray.indexOf(child1Index) === -1) {
indexToCheckArray.push(child1Index);
}
if (indexToCheckArray.indexOf(child2Index) === -1) {
indexToCheckArray.push(child2Index);
}
}
}
}
i +=1;
}
return out;
}
// In the first loop we reorder indices asc order + generate map
for (triangleIndex=0; triangleIndex<totalTriangles; triangleIndex++) {
const geoIndex1 = indexArray[triangleIndex*3];
const geoIndex2 = indexArray[triangleIndex*3+1];
const geoIndex3 = indexArray[triangleIndex*3+2];
const triangleIndexVertexArray = [ geoIndex1, geoIndex2, geoIndex3 ].sort(function(a, b) {
return a - b;
});
if (indexToTriangleIndexMap[geoIndex1] === undefined) {
indexToTriangleIndexMap[geoIndex1] = [triangleIndex];
} else {
indexToTriangleIndexMap[geoIndex1].push(triangleIndex);
}
if (indexToTriangleIndexMap[geoIndex2] === undefined) {
indexToTriangleIndexMap[geoIndex2] = [triangleIndex];
} else {
indexToTriangleIndexMap[geoIndex2].push(triangleIndex);
}
if (indexToTriangleIndexMap[geoIndex3] === undefined) {
indexToTriangleIndexMap[geoIndex3] = [triangleIndex];
} else {
indexToTriangleIndexMap[geoIndex3].push(triangleIndex);
}
//indexArray[triangleIndex*3] = triangleIndexVertexArray[0];
//indexArray[triangleIndex*3+1] = triangleIndexVertexArray[1];
//indexArray[triangleIndex*3+2] = triangleIndexVertexArray[2];
}
let geometryTriangleArray = [];
let index = 0;
while (index<indexToTriangleIndexMap.length && missingVertices>0 && missingTriangles>0){
let out = [];
if (indexVisitedArray[index] === 0) {
out = computeTriangles(index);
}
if (out.length > 0) {
geometryTriangleArray.push(out);
}
index += 1;
}
let geometryArray = [];
for (let i=0; i<geometryTriangleArray.length; i++) {
let out = {
positionArray: [],
colorArray: [],
indexArray: [],
indexMap: [],
currentIndex: 0
}
let triangleArray = geometryTriangleArray[i];
for (let j=0; j<triangleArray.length; j++) {
let triangleIndex = triangleArray[j];
let rootIndex = indexArray[triangleIndex*3];
if (out.indexMap[rootIndex] === undefined) {
out.indexMap[rootIndex] = out.currentIndex;
// add vertex position and color
out.positionArray.push(
geometry.attributes.position.array[rootIndex*3],
geometry.attributes.position.array[rootIndex*3+1],
geometry.attributes.position.array[rootIndex*3+2]
);
if (geometry.attributes.color != undefined) {
out.colorArray.push(
geometry.attributes.color.array[rootIndex*3],
geometry.attributes.color.array[rootIndex*3+1],
geometry.attributes.color.array[rootIndex*3+2]
);
}
out.currentIndex += 1;
}
let child1Index = indexArray[triangleIndex*3+1];
if (out.indexMap[child1Index] === undefined) {
out.indexMap[child1Index] = out.currentIndex;
// add vertex position and color
out.positionArray.push(
geometry.attributes.position.array[child1Index*3],
geometry.attributes.position.array[child1Index*3+1],
geometry.attributes.position.array[child1Index*3+2]
);
if (geometry.attributes.color != undefined) {
out.colorArray.push(
geometry.attributes.color.array[child1Index*3],
geometry.attributes.color.array[child1Index*3+1],
geometry.attributes.color.array[child1Index*3+2]
);
}
out.currentIndex += 1;
}
let child2Index = indexArray[triangleIndex*3+2];
if (out.indexMap[child2Index] === undefined) {
out.indexMap[child2Index] = out.currentIndex;
// add vertex position and color
out.positionArray.push(
geometry.attributes.position.array[child2Index*3],
geometry.attributes.position.array[child2Index*3+1],
geometry.attributes.position.array[child2Index*3+2]
);
if (geometry.attributes.color != undefined) {
out.colorArray.push(
geometry.attributes.color.array[child2Index*3],
geometry.attributes.color.array[child2Index*3+1],
geometry.attributes.color.array[child2Index*3+2]
);
}
out.currentIndex += 1;
}
// Add indices:
out.indexArray.push(out.indexMap[rootIndex], out.indexMap[child1Index], out.indexMap[child2Index]);
}
const geoPositions = new Float32Array(out.positionArray);
const geoColors = new Float32Array(out.colorArray);
const geoIndices = new Uint32Array(out.indexArray);
const geo = new THREE.BufferGeometry();
geo.name = "G_" + i;
geo.index = new THREE.BufferAttribute(geoIndices, 1, false);
geo.attributes.position = new THREE.BufferAttribute(geoPositions, 3, false);
geo.attributes.color = new THREE.BufferAttribute(geoColors, 3, true);
geo.computeBoundingSphere();
geo.computeBoundingBox();
geometryArray.push(geo);
}
return geometryArray;
}

Why Is My Genetic Algorithm Terrible (Why Doesn't It Converge)?

I wrote a quick experiment with a genetic algorithm. It simply takes a grid of squares and tries to mutate their color to make them all yellow. It fails miserably and I can't seem to figure out why. I've included a link to JSFiddle that demonstrates working code, as well as a copy of the code in its entirety.
http://jsfiddle.net/mankyd/X6x9L/
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<h1>The randomly flashing squares <i>should</i> be turning yellow</h1>
<div class="row">
<canvas id="input_canvas" width="100" height="100"></canvas>
<canvas id="output_canvas" width="100" height="100"></canvas>
</div>
<div class="row">
<span id="generation"></span>
<span id="best_fitness"></span>
<span id="avg_fitness"></span>
</div>
</div>
</body>
</html>
Note that the below javascript relies on jquery in a few places.
// A bit of code that draws several squares in a canvas
// and then attempts to use a genetic algorithm to slowly
// make those squares all yellow.
// Knobs that can be tweaked
var mutation_rate = 0.1; // how often should we mutate something
var crossover_rate = 0.6; // how often should we crossover two parents
var fitness_influence = 1; // affects the fitness's influence over mutation
var elitism = 1; // how many of the parent's generation to carry over
var num_offspring = 20; // how many spawn's per generation
var use_rank_selection = true; // false == roulette_selection
// Global variables for easy tracking
var children = []; // current generation
var best_spawn = null; // keeps track of our best so far
var best_fitness = null; // keeps track of our best so far
var generation = 0; // global generation counter
var clear_color = 'rgb(0,0,0)';
// used for output
var $gen_span = $('#generation');
var $best_fit = $('#best_fitness');
var $avg_fit = $('#avg_fitness');
var $input_canvas = $('#input_canvas');
var input_ctx = $input_canvas[0].getContext('2d');
var $output_canvas = $('#output_canvas');
var output_ctx = $output_canvas[0].getContext('2d');
// A spawn represents a genome - a collection of colored
// squares.
var Spawn = function(nodes) {
var _fitness = null; // a cache of our fitness
this.nodes = nodes; // the squares that make up our image
this.fitness = function() {
// fitness is simply a function of how close to yellow we are.
// This is defined through euclidian distance. Smaller fitnesses
// are better.
if (_fitness === null) {
_fitness = 0;
for (var i = 0; i < nodes.length; i++) {
_fitness += Math.pow(-nodes[i].color[0], 2) +
Math.pow(255 - nodes[i].color[1], 2) +
Math.pow(255 - nodes[i].color[2], 2);
}
_fitness /= 255*255*3*nodes.length; // divide by the worst possible distance
}
return _fitness;
};
this.mutate = function() {
// reset our cached fitness to unknown
_fitness = null;
var health = this.fitness() * fitness_influence;
var width = $output_canvas[0].width;
var height = $output_canvas[0].height;
for (var i = 0; i < nodes.length; i++) {
// Sometimes (most times) we don't mutate
if (Math.random() > mutation_rate) {
continue;
}
// Mutate the colors.
for (var j = 0; j < 3; j++) {
// colors can move by up to 32 in either direction
nodes[i].color[j] += 64 * (.5 - Math.random()) * health;
// make sure that our colors stay between 0 and 255
nodes[i].color[j] = Math.max(0, Math.min(255, nodes[i].color[j]));
}
}
};
this.draw = function(ctx) {
// This draw function is a little overly generic in that it supports
// arbitrary polygons.
ctx.save();
ctx.fillStyle = clear_color;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
for (var i = 0; i < nodes.length; i++) {
ctx.fillStyle = 'rgba(' + Math.floor(nodes[i].color[0]) + ',' + Math.floor(nodes[i].color[1]) + ',' + Math.floor(nodes[i].color[2]) + ',' + nodes[i].color[3] + ')';
ctx.beginPath();
ctx.moveTo(nodes[i].points[0][0], nodes[i].points[0][1]);
for (var j = 1; j < nodes[i].points.length; j++) {
ctx.lineTo(nodes[i].points[j][0], nodes[i].points[j][1]);
}
ctx.fill();
ctx.closePath();
}
ctx.restore();
};
};
Spawn.from_parents = function(parents) {
// Given two parents, mix them together to get another spawn
var nodes = [];
for (var i = 0; i < parents[0].nodes.length; i++) {
if (Math.random() > 0.5) {
nodes.push($.extend({}, parents[0].nodes[i]));
}
else {
nodes.push($.extend({}, parents[1].nodes[i]));
}
}
var s = new Spawn(nodes);
s.mutate();
return s;
};
Spawn.random = function(width, height) {
// Return a complete random spawn.
var nodes = [];
for (var i = 0; i < width * height; i += 10) {
var n = {
color: [Math.random() * 256, Math.random() * 256, Math.random() * 256, 1],
points: [
[i % width, Math.floor(i / width) * 10],
[(i % width) + 10, Math.floor(i / width) * 10],
[(i % width) + 10, Math.floor(i / width + 1) * 10],
[i % width, Math.floor(i / width + 1) * 10],
]
};
nodes.push(n);
}
return new Spawn(nodes);
};
var select_parents = function(gene_pool) {
if (use_rank_selection) {
return rank_selection(gene_pool);
}
return roulette_selection(gene_pool);
};
var roulette_selection = function(gene_pool) {
var mother = null;
var father = null;
gene_pool = gene_pool.slice(0);
var sum_fitness = 0;
var i = 0;
for (i = 0; i < gene_pool.length; i++) {
sum_fitness += gene_pool[i].fitness();
}
var choose = Math.floor(Math.random() * sum_fitness);
for (i = 0; i < gene_pool.length; i++) {
if (choose <= gene_pool[i].fitness()) {
mother = gene_pool[i];
break;
}
choose -= gene_pool[i].fitness();
}
// now remove the mother and repeat for the father
sum_fitness -= mother.fitness();
gene_pool.splice(i, 1);
choose = Math.floor(Math.random() * sum_fitness);
for (i = 0; i < gene_pool.length; i++) {
if (choose <= gene_pool[i].fitness()) {
father = gene_pool[i];
break;
}
choose -= gene_pool[i].fitness();
}
return [mother, father];
};
var rank_selection = function(gene_pool) {
gene_pool = gene_pool.slice(0);
gene_pool.sort(function(a, b) {
return b.fitness() - a.fitness();
});
var choose_one = function() {
var sum_fitness = (gene_pool.length + 1) * (gene_pool.length / 2);
var choose = Math.floor(Math.random() * sum_fitness);
for (var i = 0; i < gene_pool.length; i++) {
// figure out the sume of the records up to this point. if we exceed
// our chosen spot, we've found our spawn.
if ((i + 1) * (i / 2) >= choose) {
return gene_pool.splice(i, 1)[0];
}
}
return gene_pool.pop(); // last element, if for some reason we get here
};
var mother = choose_one();
var father = choose_one();
return [mother, father];
};
var start = function() {
// Initialize our first generation
var width = $output_canvas[0].width;
var height = $output_canvas[0].height;
generation = 0;
children = [];
for (var j = 0; j < num_offspring; j++) {
children.push(Spawn.random(width, height));
}
// sort by fitness so that our best comes first
children.sort(function(a, b) {
return a.fitness() - b.fitness();
});
best_spawn = children[0];
best_fitness = best_spawn.fitness();
best_spawn.draw(output_ctx);
};
var generate = function(spawn_pool) {
// generate a new set of offspring
var offspring = [];
for (var i = 0; i < num_offspring; i++) {
var parents = select_parents(spawn_pool);
// odds of crossover decrease as we get closer
if (Math.random() * best_fitness < crossover_rate) {
var s = Spawn.from_parents(parents);
}
else {
// quick hack to copy our mother, with possible mutation
var s = Spawn.from_parents([parents[0], parents[0]]);
}
offspring.push(s);
}
// select a number of best from the parent pool (elitism)
for (var i = 0; i < elitism; i++) {
offspring.push(spawn_pool[i]);
}
// sort our offspring by fitness (this includes the parents from elitism). Fittest first.
offspring.sort(function(a, b) {
return a.fitness() - b.fitness();
});
// pick off the number that we want
offspring = offspring.slice(0, num_offspring);
best_spawn = offspring[0];
best_fitness = best_spawn.fitness();
best_spawn.draw(output_ctx);
generation++;
return offspring;
};
var average_fitness = function(generation) {
debugger;
var a = 0;
for (var i = 0; i < generation.length; i++) {
a += generation[i].fitness();
}
return a / generation.length;
};
//Draw yellow and then initialize our first generation
input_ctx.fillStyle = 'yellow';
input_ctx.fillRect(0, 0, input_ctx.canvas.width, input_ctx.canvas.height);
start();
// Our loop function. Use setTimeout to prevent things from freezing
var gen = function() {
children = generate(children);
$gen_span.text('Generation: ' + generation);
$best_fit.text('Best Fitness: ' + best_fitness);
$avg_fit.text('Avg. Fitness: ' + average_fitness(children));
if (generation % 100 === 0) {
console.log('Generation', generation);
console.log('Fitness', best_fitness);
}
setTimeout(gen, 1);
};
gen();​
I've commented the code to try to make parsing it easy. The basic idea is quite simple:
Select 1 or 2 parents from the current generation
Mix those one or two parents together
Mutate the result slightly and add it to the next generation
Select the best few parents (1 in the example) and add them to the next generation
Sort and slice off N results and use them for the next generation (potentially a mix of parents and offspring)
Rinse and repeat
The output never gets anywhere near yellow. It quickly falls into a steady state of a sort that looks awful. Where have I gone wrong?
Solved it. It was in the "from_parents" method:
if (Math.random() > 0.5) {
nodes.push($.extend({}, parents[0].nodes[i]));
}
else {
nodes.push($.extend({}, parents[1].nodes[i]));
}
The $.extend() was doing a shallow copy. The obvious solution was to either put true as the first argument which causes a deep copy. This, however, is incredibly slow performance-wise. The better solution was to remove the $.extend() from that chunk of code entirely and instead to move it up to the mutate() method, where I call $.extend() only if a node is actually about to be changed. In other words, it becomes a copy-on-write.
Also, the color I put in the fitness function was wrong :P

How to run a function once in $ (window).scroll()?

I'm trying to make a page that launches different animation depending on the scroll.
The principle is simple, when I'm in a block with a data-attribute concerning the type of animation. I run this animation.
To do this, my script is based on the event $(window).scroll().
When my $(window).scrollTop() is equal to the position of my block, I run the animation. When I leave this block I stop the animation. I would like once the animation is complete, start once my reset function. Currently, she embarked loop as I am not in a block with a data-attribute.
A demo
I'm really stuck. Thank you in advance. Manu
my js file :
$(document).ready(init);
// Ma class Screen
function Screen(name){
this._name = $("#"+name);
this._hauteur;
this._position;
this._screenEnd;
this._screenEnd;
this.screenHeight = function() {
this._hauteur = this._name.data('height');
return this._hauteur;
}
this.topPosition = function() {
this._position = this._name.position().top;
return this._position;
}
this.screenEnd = function() {
this._screenEnd = (this._name.position().top)+(this._name.data('height'));
return this._screenEnd;
}
}
var mesScreens = new Array();
$(".screen").each(function(i){
mesScreens[i] = new Screen($(this).attr('id'));
mesScreens[i]._name.css("height", mesScreens[i].screenHeight());
//console.log(mesScreens[i]);
});
var fini = false;
function init(){
console.log($(".screen").length);
var scrollTimer = null;
$(window).scroll(function () {
var monScrollTop = $(window).scrollTop();
for (var i=0; i<mesScreens.length ; i++) {
if(monScrollTop>(mesScreens[i].topPosition()+5) && monScrollTop<=(mesScreens[i].screenEnd()+5)){
//started = true;
if(mesScreens[i]._name.data("func") == "panorama"){
horizontalPanel(mesScreens[i]._name, mesScreens[i]._hauteur, mesScreens[i]._position);
}else if(mesScreens[i]._name.data("func") == "anim"){
anim(mesScreens[i]._name, mesScreens[i]._hauteur, mesScreens[i]._position, 4);
}
//console.log(mesScreens[3]._hauteur);
}else {
//console.log("je sors");
reset(mesScreens[i]._name, mesScreens[i]._hauteur);
}
};
});
}
/*
* Function horizontalPanel
* #screen : le screen concerné
* #hauteur : hauteur du div
*/
function horizontalPanel(myScreen, hauteur, position){
//console.log("Fonction horizontalPanel debut || fini = "+fini);
var $img = myScreen.children("img");
var deltaScroll = ($(window).scrollTop() - position);
var scrollPercentage = ((deltaScroll / (hauteur)) * 100) ;
//console.log(scrollPercentage);
$img.css('position', "fixed");
$img.css("bottom", "");
$img.css('top', "0px");
$img.css('left', "0px");
$img.css("left", -scrollPercentage+"%");
}
function anim(myScreen, hauteur, position, nbImg){
//console.log("ok");
var $img = myScreen.children("div.image");
var deltaScroll = ($(window).scrollTop() - position);
var scrollPercentage = ((deltaScroll / (hauteur)) * 100) ;
var percentNb = ((nbImg/hauteur) * 100).toFixed(2);
for(var i=0; i<nbImg; i++){
//console.log("if(bla)");
}
//console.log("__");
if(scrollPercentage)
//console.log(hauteur);
$img.css('position', "fixed");
$img.css("top", "0px");
$img.css("bottom", "");
$img.css('background-position', "0 "+ scrollPercentage + '%');
$img.css('left', "0px");
}
function reset(myScreen){
//console.log("Fonction Reset || fini = "+fini);
myScreen.children().css('position', "relative");
myScreen.children().css("bottom", "0px");
myScreen.children().css("top", "");
myScreen.children().css("left", "");
}
An extract from html :
<div id="screen3" data-height='2300' data-func='panorama' class="screen">
<img src="img/screen3.jpg" alt="screen-3">
</div>
<div id="screen4">
<img src="img/screen4-2.jpg" alt="screen-4">
</div>

Resources