Code doesn't work when inside the function - javascript

I have code that works well when used outside a function. But not sure what goes wrong when I just wrap a function around it.
This is my working code: Idea is to move the pencil in a square path. In the working code, it follows the square path but when I wrap around the function, it keeps going on in a straight line.
var direction ='right';
var angle = 0;
var sum_angle = 0;
for (var count = 0; count < 5; count++) {
if(--window.LoopTrap == 0) throw "Infinite loop.";
move_draw_Player(direction, 100);
var new_angle=90;
$('#player').animate({rotate: '90deg'}, 100);
var angle=angle +new_angle;
sum_angle =sum_angle + angle;
}
function move_draw_Player(directionStr, amount) {
directionStr =angle;
var x = Math.sin(angle*Math.PI/-180) * amount;
var y = Math.cos(angle*Math.PI/-180) * amount;
z= amount/100;
$('#pencil').animate({'left': '-='+x+'px', 'top': '-='+y+'px'}, z*350, 'linear', function() {
//window.counter = window.counter +2;
pen.moveTo((pencil.offset().left - cw.offset().left),(pencil.offset().top+ pencil.height() -ac.offset().top));
});
But when I wrap a function around it, it doesn't work. What could be going wrong?
var direction ='right';
var angle = 0;
var sum_angle = 0;
function Draw_Square() {
for (var count = 0; count < 5; count++) {
if(--window.LoopTrap == 0) throw "Infinite loop.";
move_draw_Player(direction, 100);
var new_angle=90;
$('#player').animate({rotate: '90deg'}, 100);
var angle=angle +new_angle;
sum_angle =sum_angle + angle;
}
}
function move_draw_Player(directionStr, amount) {
directionStr =angle;
var x = Math.sin(angle*Math.PI/-180) * amount;
var y = Math.cos(angle*Math.PI/-180) * amount;
z= amount/100;
$('#pencil').animate({'left': '-='+x+'px', 'top': '-='+y+'px'}, z*350, 'linear', function() {
//window.counter = window.counter +2;
pen.moveTo((pencil.offset().left - cw.offset().left),(pencil.offset().top+ pencil.height() -ac.offset().top));
});
}
//}
Draw_Square();

Related

Paint bucket getting "Maximum Call Stack Size Exceeded" error

This is the code of the paint bucket tool in my drawing app using the p5.js library. The function self.floodFill always get "Maximum Call Stack Size Exceeded" because of recursion and I want to know the way to fix it. I am thinking if changing the function to a no recursion function would help or not. Any help would be appreciated.
function BucketTool(){
var self = this;
//set an icon and a name for the object
self.icon = "assets/bucket.jpg";
self.name = "Bucket";
var d = pixelDensity();
var oldColor;
var searchDirections = [[1,0],[-1,0],[0,1],[0,-1]];
var pixelsToFill = [];
var positionArray = new Array(2);
self.checkBoundary = function(currentX, currentY, localOldColor) {
if (self.getPixelAtXYPosition(currentX,currentY).toString() != localOldColor.toString() || currentX < 0 || currentY < 0 || currentX > width || currentY > height || pixelsToFill.indexOf(currentX+" "+currentY) != -1) {
return false;
}
return true;
};
self.floodFill = function(currentX, currentY, localOldColor, localSearchDirections) {
if (self.checkBoundary(currentX, currentY, localOldColor)){
pixelsToFill.push(currentX+" "+currentY);
} else {
return;
}
for (var i = 0; i < searchDirections.length; i++){
self.floodFill(currentX + searchDirections[i][0], currentY + searchDirections[i][1], localOldColor, localSearchDirections);
}
};
self.getPixelAtXYPosition = function(x, y) {
var colour = [];
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
// loop over
index = 4 * ((y * d + j) * width * d + (x * d + i));
colour[0] = pixels[index];
colour[1] = pixels[index+1];
colour[2] = pixels[index+2];
colour[3] = pixels[index+3];
}
}
return colour;
}
self.drawTheNeededPixels = function(){
for(var i = 0; i < pixelsToFill.length; i++){
positionArray = pixelsToFill[i].split(" ");
point(positionArray[0],positionArray[1]);
}
}
self.draw = function () {
if(mouseIsPressed){
pixelsToFill = [];
loadPixels();
oldColor = self.getPixelAtXYPosition(mouseX, mouseY);
self.floodFill(mouseX, mouseY, oldColor, searchDirections);
self.drawTheNeededPixels();
}
};
}
This problem is well documented on the wikipedia page and the shortfalls of the different types of algorithms to perform flood filling. You've gone for the stack-based recursive implementation.
To prevent a stackoverflow — Maximum Call Stack Exceeded — the first step would be to use a data structure. Using queues/stacks rather than having the function call itself.
The code below creates an empty stack where we put a new object containing the x and y where the user has chosen to fill. This is then added to the pixelsToFill array. We then loop the stack until it's completely empty, at which point we are ready to display the filled pixels.
In the while loop we pop an element off the stack and then find its children — the directions up, down, left, right denoted by the searchDirections array you created. If we've not seen the child before and it's within the boundary we add it to the pixelsToFill array and add it to the stack to repeat the process:
self.floodFill = function (currentX, currentY, localOldColor, localSearchDirections) {
let stack = [];
stack.push({ x: currentX, y: currentY });
pixelsToFill.push(currentX + " " + currentY);
while (stack.length > 0) {
let current = stack.pop();
for (var i = 0; i < searchDirections.length; i++) {
let child = {
x: current.x + searchDirections[i][0],
y: current.y + searchDirections[i][1],
localOldColor,
};
if (self.checkBoundary(child.x, child.y, localOldColor)) {
pixelsToFill.push(child.x + " " + child.y);
stack.push(child);
}
}
}
};
This code may stop the stackoverflow but there are still a lot of optimisations that can be made. Once again, it's worth checking out the Wikipedia page and potentially take a look at Span filling.
let bucketTool;
function setup() {
createCanvas(400, 400);
bucketTool = new BucketTool();
}
function draw() {
background(220);
strokeWeight(5);
circle(width / 2, height / 2, 100);
frameRate(1);
bucketTool.draw();
}
function BucketTool() {
var self = this;
//set an icon and a name for the object
// self.icon = "assets/bucket.jpg";
// self.name = "Bucket";
var d = pixelDensity();
var oldColor;
var searchDirections = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1],
];
var pixelsToFill = [];
var positionArray = new Array(2);
self.checkBoundary = function (currentX, currentY, localOldColor) {
if (
self.getPixelAtXYPosition(currentX, currentY).toString() !=
localOldColor.toString() ||
currentX < 0 ||
currentY < 0 ||
currentX > width ||
currentY > height ||
pixelsToFill.indexOf(currentX+" "+currentY) != -1
) {
return false;
}
return true;
};
self.floodFill = function (currentX, currentY, localOldColor, localSearchDirections) {
let stack = [];
stack.push({ x: currentX, y: currentY });
pixelsToFill.push(currentX + " " + currentY);
while (stack.length > 0) {
let current = stack.pop();
for (var i = 0; i < searchDirections.length; i++) {
let child = {
x: current.x + searchDirections[i][0],
y: current.y + searchDirections[i][1],
localOldColor,
};
if (self.checkBoundary(child.x, child.y, localOldColor)) {
pixelsToFill.push(child.x + " " + child.y);
stack.push(child);
}
}
}
};
self.getPixelAtXYPosition = function (x, y) {
var colour = [];
for (var i = 0; i < d; i++) {
for (var j = 0; j < d; j++) {
// loop over
index = 4 * ((y * d + j) * width * d + (x * d + i));
colour[0] = pixels[index];
colour[1] = pixels[index + 1];
colour[2] = pixels[index + 2];
colour[3] = pixels[index + 3];
}
}
return colour;
};
self.drawTheNeededPixels = function () {
for (var i = 0; i < pixelsToFill.length; i++) {
positionArray = pixelsToFill[i].split(" ");
point(positionArray[0], positionArray[1]);
}
};
self.draw = function () {
if (mouseIsPressed) {
pixelsToFill = [];
loadPixels();
oldColor = self.getPixelAtXYPosition(mouseX, mouseY);
self.floodFill(mouseX, mouseY, oldColor, searchDirections);
console.log(pixelsToFill.length);
self.drawTheNeededPixels();
}
};
}
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<main>
</main>
<script src="sketch.js"></script>
</body>
</html>
Shameless plug, but relevant: I've created a blog comparing the different flood fill algorithms using p5.js.

Processes for optimizing canvas animations

I've got a small web app in development to simulate the Ising model of magnetism. I've found that the animation slows down considerably after a few seconds of running, and it also doesn't loop after 5 seconds like I want it to with the command:
setInteval(main, 500)
I've added start and stop buttons. When I stop the animation, and then restart it, it begins fresh at the usual speed, but again slows down.
My question is: what steps can I take to troubleshoot and optimize the performance of my canvas animation? I hope to reduce or mitigate this slowing effect.
JS code:
window.onload = function() {
var canvas = document.getElementById("theCanvas");
var context = canvas.getContext("2d");
var clength = 100;
var temperature = 2.1;
var playAnim = true;
canvas.width = clength;
canvas.height = clength;
var imageData = context.createImageData(clength, clength);
document.getElementById("stop").addEventListener("click",function(){playAnim=false;});
document.getElementById("start").addEventListener("click",function(){playAnim=true;});
function init2DArray(xlen, ylen, factoryFn) {
//generates a 2D array of xlen X ylen, filling each element with values defined by factoryFn, if called.
var ret = []
for (var x = 0; x < xlen; x++) {
ret[x] = []
for (var y = 0; y < ylen; y++) {
ret[x][y] = factoryFn(x, y)
}
}
return ret;
}
function createImage(array, ilen, jlen) {
for (var i = 0; i < ilen; i++) {
for (var j = 0; j < jlen; j++) {
var pixelIndex = (j * ilen + i) * 4;
if (array[i][j] == 1) {
imageData.data[pixelIndex] = 0; //r
imageData.data[pixelIndex+1] = 0; //g
imageData.data[pixelIndex+2] = 0; //b
imageData.data[pixelIndex+3] = 255; //alpha (255 is fully visible)
//black
} else if (array[i][j] == -1) {
imageData.data[pixelIndex] = 255; //r
imageData.data[pixelIndex+1] = 255; //g
imageData.data[pixelIndex+2] = 255; //b
imageData.data[pixelIndex+3] = 255; //alpha (255 is fully visible)
//white
}
}
}
}
function dU(i, j, array, length) {
var m = length-1;
//periodic boundary conditions
if (i == 0) { //top row
var top = array[m][j];
} else {
var top = array[i-1][j];
}
if (i == m) { //bottom row
var bottom = array[0][j];
} else {
var bottom = array[i+1][j];
}
if (j == 0) { //first in row (left)
var left = array[i][m];
} else {
var left = array[i][j-1];
}
if (j == m) { //last in row (right)
var right = array[i][0];
} else {
var right = array[i][j+1]
}
return 2.0*array[i][j]*(top+bottom+left+right); //local magnetization
}
function randInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
var myArray = init2DArray(clength, clength, function() {var c=[-1,1]; return c[Math.floor(Math.random()*2)]}); //creates a 2D square array populated with -1 and 1
function main(frame) {
if (!playAnim){return;} // stops
window.requestAnimationFrame(main);
createImage(myArray, clength, clength);
context.clearRect(0,0,clength,clength);
context.beginPath();
context.putImageData(imageData,0,0);
for (var z = 0; z < 10*Math.pow(clength,2); z++) {
i = randInt(clength-1);
j = randInt(clength-1);
var deltaU = dU(i, j, myArray, clength);
if (deltaU <= 0) {
myArray[i][j] = -myArray[i][j];
} else {
if (Math.random() < Math.exp(-deltaU/temperature)) {
myArray[i][j] = -myArray[i][j];
}
}
}
}
var timer = setInterval(main, 500);
}

Randomize/shuffle cards in stack with jQuery

I am building a very simple memory game for a small project. The logic is as follows:
click on the input field to choose with how many pairs would you like to play
create divs with classes card1, card2 etc.
clone divs and randomize their place in the array
Here is my script (fork in JSFiddle):
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
for (var i = 0; i < cards.length; i++) {
var target = Math.floor(Math.random() * cards.length - 1) + 1;
var target2 = Math.floor(Math.random() * cards.length - 1) + 1;
var target3 = Math.floor(Math.random() * cards.length - 1) + 1;
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
}
});
what I need now is to adjust the 3rd step, meaning to dynamically create the target vars, and the last line of the code
cards.eq(target).before(cards.eq(target2)).before(cards.eq(target3));
So please make me a suggestion - how would you do it? And bare in mind this is a project for beginners. Thank you!
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
var parent = $(".container");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
see jsfidle: http://jsfiddle.net/007y4rju/8/
source: http://jsfiddle.net/C6LPY/2/
Here is the version of the code in jsfiddle - http://jsfiddle.net/007y4rju/6/
Please, check if the behavior is consistent with the original code.
$(document).ready(function () {
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>") &&
$(".card" + i).clone().appendTo(".container");
}
// randomize cards in stack
var cards = $(".cards");
var startTarget = Math.floor(Math.random() * cards.length - 1) + 1;
var collection = cards.eq(startTarget);
var nextTarget;
var i;
for (i = 0; i < cards.length; i++) {
nextTarget = Math.floor(Math.random() * cards.length - 1) + 1;
collection.before(cards.eq(nextTarget));
}
});
});
You can randomize index in a class name (card%i%) when cloning divs. Then you don't need to shuffle cloned divs; you can append them as is.
$(".button").click(function () {
// get the value from the input
var numCards = parseInt($('input').val());
for (var i = 1; i <= numCards; i++) {
// create the cards
$(".container").append("<div class='card" + i + " cards'></div>");
}
var aIndices = [];
for (var i = 1; i <= numCards; i++) {
var ix;
do ix = Math.round(Math.random() * (numCards - 1)) + 1;
while (aIndices.indexOf(ix) >= 0);
aIndices.push(ix);
// clone
$(".card" + ix).clone().appendTo(".container");
}
});

Callbacks on Asynchronous Functions with SetInterval?

I'm trying to get something to run after a function using setInterval is done. I'm trying to do this with callbacks but I can't seem to get it work?
So far I have the following
var testing = ['A','D','F','H','B'];
var index = 0;
var wordCount = 1;
var showHide = setInterval(function () {
var displayWords = "";
var mx = index + wordCount;
if (mx > testing.length) mx = testing.length;
for (var i = index; i < mx; i++) {
displayWords += testing[i] + " ";
}
d3.select("#stim").text(displayWords).style("font-size","150px");
index = mx;
if (index > testing.length) {
clearInterval(showHide);
d3.select("#stim").text('L,R').style("font-size","150px");
}
}, 1000);
And I want the following line to execute "after":
d3.select("#stim").text('L,R').style("font-size","150px");
I tried using this method but when I try to put "showHide" in its own function, it doesn't seem to work at all.

JavaScript Timing

I want to select all the elements of a class. Then change that class to another class . After 0.5 seconds i want to revert the elements back to their original class. I must do this 8 times in a row. Even though my code achieves that(in a way) i can't see the color changes in the buttons . Can anyone help me ? it's a timing problem i guess. Here is the js code :
$(document).ready(function(){
$('#start').click(function(){
game();
})
function game(){
var ordine = new Array();
for(var t = 1; t <= 8; t++){
var y = 0;
for (var k = 0; k < t; k++) {
var x = Math.floor((Math.random() * 4) + 1);
ordine[y++] = x;
change1(x);
setTimeout(change2(x), 500);
}
}
}
function change1(y){
var z = 'cls' + y;
var t = 'cls' + y + 2;
$("." + z).removeClass(z).addClass(t);
}
function change2(y){
var z = 'cls' + y + 2;
var t = 'cls' + y;
$("." + z).removeClass(z).addClass(t);
}
})
Here you can find the full code(html,css and js)
http://jsfiddle.net/Cx5VK/2/
The problem is in the following line:
setTimeout(change2(x), 500);
You are calling the function change2 here, passing its return value to setTimeout.
What you actually want though is to call the change2 function after 500ms. Change your code to:
setTimeout(function() { change2(x); }, 500);
That way, you are passing an anonymous function to setTimout, which will then be executed by it after 500ms.
EDIT: I've modified your JSFiddle: http://jsfiddle.net/Cx5VK/7/ stripping out a lot of code that didn't do anything in that sample (you quite possibly need it elsewhere):
$(document).ready(function () {
$('#start').click(function () {
game();
})
function game() {
var x = Math.floor((Math.random() * 4) + 1);
change1(x);
}
function change1(y) {
var z = 'cls' + y;
var t = 'cls' + y + 2;
$("." + z).removeClass(z).addClass(t);
setTimeout(function() { change2(y); }, 500);
}
function change2(y) {
var z = 'cls' + y + 2;
var t = 'cls' + y;
$("." + z).removeClass(z).addClass(t);
game();
}
});
Now, the game function simply gets a random number and calls change1 with that number as parameter. change1 itself will set the timeout to reset the color for that square via change2. At the end of that function, the game is "restarted" by a simple call to game(), to get another random number and so on and so forth. I hope this is what you were looking for.

Categories