making a variable string a function name - javascript

I was wondering if there was a way to make a var value a function. I'm currently working on a project that makes scripts and runs the code, but when all the function names are the same instead of the two scripts running independent code their writing the same code in unison. If you could show me how to do this it would be a huge help! But I'm not exactly sure if its possible. None the less heres some code
var update = setInterval(function(){
checkDotPop();
sc();
}, 1);
var canvas = document.getElementById("canvas");
var body = document.getElementById("body");
totalDots = 2;
aliveDots = 1;
//styling
body.style.border = "0px";
canvas.style.backgroundColor = "black";
function checkDotPop(){
while(aliveDots != totalDots){
makeDot();
aliveDots++;
}
}
function makeDot(){
var scr = document.createElement("script");
scr.setAttribute("id", "dot" + totalDots);
document.body.appendChild(scr);
var script = document.getElementById("dot" + totalDots);
script.innerHTML = "var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var rand1; var rand2; function changeRand(){rand1 = Math.floor(Math.random() * 300) + 1; rand2 = Math.floor(Math.random() * 300) + 1;} function sc(){ changeRand(); context.fillStyle = 'red'; context.fillRect(rand1, rand2, 10, 10); context.fill();";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body id="body">
<canvas id="canvas" height="500px" width="500px"/>
</body>
</html>
It'll say that "sc is not defined" but in the version I have (using notepad) sc is a gobal function and can be called from script to script

You where missing a closing bracket for your sc function.
var update = setInterval(function(){
checkDotPop();
sc();
}, 1);
var canvas = document.getElementById("canvas");
var body = document.getElementById("body");
totalDots = 2;
aliveDots = 1;
//styling
body.style.border = "0px";
canvas.style.backgroundColor = "black";
function checkDotPop(){
while(aliveDots != totalDots){
makeDot();
aliveDots++;
}
}
function makeDot(){
var scr = document.createElement("script");
scr.setAttribute("id", "dot" + totalDots);
document.body.appendChild(scr);
var script = document.getElementById("dot" + totalDots);
script.innerHTML = "var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var rand1; var rand2; function changeRand(){rand1 = Math.floor(Math.random() * 300) + 1; rand2 = Math.floor(Math.random() * 300) + 1;} function sc(){ changeRand(); context.fillStyle = 'red'; context.fillRect(rand1, rand2, 10, 10); context.fill();}";
}
<!DOCTYPE html>
<html>
<head>
</head>
<body id="body">
<canvas id="canvas" height="500px" width="500px"/>
</body>
</html>

Related

javascript: uncaught reference error

I am making a javascript game, using Canvas. However, I got that error(below image) and background image is not shown. I suspect below 4 files, because other files didn't make any trouble. I guess the problem is related with game_state...how can I solve the problem??
I am agonizing for 2days:( plz, help me..
error image1
error image2
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>Lion Travel</title>
<!--GameFramework-->
<script src="/.c9/gfw/GameFramework.js"></script>
<script src="/.c9/gfw/FrameCounter.js"></script>
<script src="/.c9/gfw/InputSystem.js"></script>
<script src="/.c9/gfw/SoundManager.js"></script>
<script src="/.c9/gfw/GraphicObject.js"></script>
<script src="/.c9/gfw/SpriteAnimation.js"></script>
<script src="/.c9/gfw/ResourcePreLoader.js"></script>
<script src="/.c9/gfw/DebugSystem.js"></script>
<script src="/.c9/gfw/Timer.js"></script>
<script src="/.c9/gfw/FrameSkipper.js"></script>
<script src="/.c9/gfw/TransitionState.js"></script>
<!--GameInit-->
<script src="/.c9/gfw/gfw.js"></script>
<!--Game Logic-->
<script src="/.c9/RS_Title.js"></script>
</head>
<body>
<canvas id="GameCanvas" width="800" height="600">html5 canvas is not supported.</canvas>
</body>
</html>
gfw.js
function onGameInit() {
document.title = "Lion Travel";
GAME_FPS = 30;
debugSystem.debugMode = true;
resourcePreLoader.AddImage("/.c9/title_background.png");
soundSystem.AddSound("/.c9/background.mp3", 1);
after_loading_state = new TitleState();
setInterval(gameLoop, 1000 / GAME_FPS);
}
window.addEventListener("load", onGameInit, false);
RS_Title.js
function TitleState()
{
this.imgBackground = resourcePreLoader.GetImage("/.c9/title_background.png");
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
return this;
}
TitleState.prototype.Init = function()
{
soundSystem.PlayBackgroundMusic("/.c9/background.mp3");
};
TitleState.prototype.Render = function()
{
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
//drawing backgroundimage
Context.drawImage(this.imgBackground, 0, 0);
};
TitleState.prototype.Update = function()
{
};
GameFramework.js
var GAME_FPS;
var game_state = after_loading_state;
function ChangeGameState(nextGameState)
{
//checking essential function
if(nextGameState.Init == undefined)
return;
if(nextGameState.Update == undefined)
return;
if(nextGameState.Render == undefined)
return;
game_state = nextGameState;
game_state.Init();
}
function Update()
{
timerSystem.Update();
game_state.Update();
debugSystem.UseDebugMode();
}
function Render()
{
//drawing
var theCanvas = document.getElementById("GameCanvas");
var Context = theCanvas.getContext("2d");
Context.fillStyle = "#000000";
Context.fillRect(0, 0, 800, 600);
//game state
game_state.Render();
if(debugSystem.debugMode)
{
//showing fps
Context.fillStyle = "#ffffff";
Context.font = '15px Arial';
Context.textBaseline = "top";
Context.fillText("fps: "+ frameCounter.Lastfps, 10, 10);
}
}
function gameLoop()
{
Update();
Render();
frameCounter.countFrame();
}
The issue here is that you are initializing game_state with the object after_loading_state even before after_loading_state is initialized(which is initialized only after the document is loaded). Due to this game_state remains undefined.
To fix this, change var game_state = after_loading_state; in GameFramework.js to var game_state;. And add game_state = after_loading_state; as the first line in gameLoop function. This way, the initialization of variables occur in the correct order.

drawing more on the canvas without having to create more script tags

I've been attempting to create a ecology simulation and so far its been going good. The code below does work I'm just wondering if theres an easier way to draw more items on the canvas with code instead of manually doing it. The way I'm doing it makes me consider the lag because I will be adding a lot to the code (e.g. move, detected, reproduce, chase, run, etc). Thank you for seeing this
//This tag will regulate the spawning of new sheep/wolves
var totalWolves = 0;
var totalSheep = 0;
var canavs = document.getElementById("canvas");
var body = document.getElementById("body");
//styler
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
function spawnWolves(){
totalWolves++;
var name = "wolf" + totalWolves;
var scrpt = document.createElement("SCRIPT");
document.body.appendChild(scrpt);
scrpt.setAttribute("id", name);
var script = document.getElementById(name);
script.innerHTML = "var rand3 = Math.floor(Math.random() * 100) + 1; var rand4 = Math.floor(Math.random() * 100) + 1; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = 'red'; context.fillRect(rand3, rand4, 10, 10); context.fill();";
}
spawnWolves();
spawnWolves();
spawnWolves();
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
<script>
</script>
</body>
</html>
Your solution seems very complicated ...
Please, take a look at the following code.
<!DOCTYPE html>
<html>
<title>AI spawn test</title>
<canvas id="canvas" width="110" height="110"></canvas>
<script>
var ctx = canvas.getContext("2d");
var drawRect=function(rects){
for (var i=1; i<=rects; i++){
var rand3=Math.floor(Math.random() * 100) + 1;
var rand4=Math.floor(Math.random() * 100) + 1;
ctx.fillStyle='red';
ctx.fillRect(rand3, rand4, 10, 10)
}
}
drawRect(20);
</script>
This type of 'replication' is done by using loop. There are several loop types, but their explanation is too broad. You can browse the net.
I gave you 2 examples below - with for loop and with while loop.
//This tag will regulate the spawning of new sheep/wolves
var totalWolves = 0;
var totalSheep = 0;
var canavs = document.getElementById("canvas");
var body = document.getElementById("body");
//styler
body.style.overflow = "hidden";
body.style.margin = "0px";
canvas.style.backgroundColor = "black";
function spawnWolves(){
totalWolves++;
var name = "wolf" + totalWolves;
var scrpt = document.createElement("SCRIPT");
document.body.appendChild(scrpt);
scrpt.setAttribute("id", name);
var script = document.getElementById(name);
script.innerHTML = "var rand3 = Math.floor(Math.random() * 100) + 1; var rand4 = Math.floor(Math.random() * 100) + 1; var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = 'red'; context.fillRect(rand3, rand4, 10, 10); context.fill();";
}
for(var i=0; i<12; i++)
{
spawnWolves();
}
var maxWolves=9;
while(totalWolves < maxWolves)
{
spawnWolves();
}
<!DOCTYPE html>
<html>
<head>
<title>AI spawn test</title>
</head>
<body id="body">
<canvas id="canvas" width="1366px" height="768px"/>
<script>
</script>
</body>
</html>
The first loop will run until its internal counter i goes from 0 to 12 and will call the function exactly 12 times.
The second loop will run as long as the condition totalWolves < maxWolves is true. totalWolves is your counter you increase in your function and maxWolves is the limit when you want the loop to stop.
Because these 2 examples are added here one after another the second wont work. After the first one executes you will already have 12 wolves and the second loop will not enter because 12 < 9 is false.

how to get element inside frame? (to draw canvas)

Page for Example:
http://google.com/recaptcha/api2/demo
If i open the image 'myid' the frame will be - EXAMPLE:frame2
now what i want to do, is to draw canvas of 'myid' inside the 'frame2'.
here is the code that i have: (draw by element id)
var canvas = window.document.createElementNS('http://www.w3.org/1999/xhtml', 'html:canvas');
var selection_element = window.document.getElementById("myid");
var selection;
var de = window.document.documentElement;
var box = selection_element.getBoundingClientRect();
var new_top = box.top + window.pageYOffset - de.clientTop;
var new_left = box.left + window.pageXOffset - de.clientLeft;
var new_height = selection_element.offsetHeight;
var new_width = selection_element.offsetWidth;
selection={
top:new_top,
left:new_left,
width:new_width,
height:new_height,
};
canvas.height = selection.height;
canvas.width = selection.width;
var context = canvas.getContext('2d');
context.drawWindow(
window,
selection.left,
selection.top,
selection.width,
selection.height,
'rgba(255, 255, 255, 0)'
);
var canvasdata = canvas.toDataURL('','').split(',')[1];
To append item to frame you need to call that by id. In this HTML:
<iframe id="frm1"></iframe>
<iframe id="frm2"></iframe>
If you use this code:
$(document).ready(function ()
{
var frames = window.frames;
for (var i = 0; i < frames.length; i++)
{
var fi = frames[i]
$(fi).load(function ()
{
$(this).contents().find('body').append("<span>Hello World!</span>");
});
}
});
Does not work, But this one works:
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<iframe id="frm1"></iframe>
<iframe id="frm2"></iframe>
<script>
$(document).ready(function ()
{
var frm1 = window.frames["frm1"];
$(frm1).load(function ()
{
$(frm1).contents().find('body').append("<span>Hello World!</span>");
});
});
</script>
</body></html>
I tried to create a code snippet, but it seems it has problem with frames.
You can copy the exact HTML and test that.

JavaScript text wont display

I've been working on a simple matching puzzle game for a little while now. Currently I have been able to have a countdown time and the number of matching tiles displayed as a text and I'm trying to create one for the best time completed (basically how fast the person completed the puzzle). However whenever I try to create it the text never displays.I noticed while writing the code that if I where to place the variable "txt" followed by a "." the autocomplete box will appear with .text as an available option so I would get "txt.text". I do not however get that option when writing the bestTimeTxt variable which is what I am using to display the time. I'm not sure what I have done wrong, here is my code.
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_value = 255;
var gray = Graphics.getRGB(20, 20, 20);
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var bestTime;
var bestTimeTxt;
var matchesFoundText;
var squares;
function init() {
var rows = 5;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
var numberOfTiles = rows*columns;
matchesFound = 0;
timeAllowable = 5;
bestTime = 0
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top"; // draw text relative to the top of the em box.
txt.x = 500;
txt.y = 0;
bestTimeTxt = new Text(bestTime, "30px Monospace", "#000");
bestTimeTxt.textBaseLine = "top";
bestTimeTxt.x = 300;
bestTimeTxt.y = 0;
stage.addChild(txt);
stage.addChild(bestTimeTxt);
squares = [];
totalMatchesPossible = numberOfTiles/2;
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
matchesFoundText = new Text("Pairs Found: "+matchesFound+"/"+totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top"; // draw text relative to the top of the em box.
matchesFoundText.x = 500;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if (i % 2 === 0){
var color = randomColor();
}
var square = drawSquare(gray);
square.color = color;
square.x = (squareSide+squarePadding) * (placement % columns);
square.y = (squareSide+squarePadding) * Math.floor(placement / columns);
squares.push(square);
stage.addChild(square);
square.cache(0, 0, squareSide + squarePadding, squareSide + squarePadding);
square.onPress = handleOnPress;
stage.update();
};
}
function drawSquare(color) {
var shape = new Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*255);
var color2 = Math.floor(Math.random()*255);
var color3 = Math.floor(Math.random()*255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles){
for(var i = 0;i< numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
tile.graphics.beginFill(tile.color).rect(squareOutline, squareOutline, squareSide, squareSide);
if(!!tileClicked === false || tileClicked === tile){
tileClicked = tile;
tileClicked.updateCache("source-overlay");
}else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = "Pairs Found: "+matchesFound+"/"+totalMatchesPossible;
if (matchesFound===totalMatchesPossible){
gameOver(true);
}
}else{
tileClicked.graphics.beginFill(gray).rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked.updateCache("source-overlay");
tile.updateCache("source-overlay");
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable-Ticker.getTime()/1000));
txt.text = secondsLeft;
bestTimeTxt.text = "test";
if (secondsLeft <= 0){
gameOver(false);
}
stage.update();
}
function gameOver(win){
Ticker.setPaused(true);
for(var i=0;i<squares.length;i++){
squares[i].graphics.beginFill(squares[i].color).rect(5, 5, 70, 70);
squares[i].onPress = null;
if (win === false){
squares[i].uncache();
}
}
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
if (win === true){
matchesFoundText.text = "You win!"
}else{
txt.text = secondsLeft + "... Game Over";
}
}
function replay(){
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
Apparently the issue I was having was that the x and y position of the text was causing it to appear behind everything else.

JavaScript Variable wont stop reverting back to 0

I'm currently working on a small tile matching game and have made it so that each time you complete the game the variable "bestTime" will store the amount of time you took to complete the session. The variable "bestTimeTxt" will then take the value and display it in text. After you have completed a session a link will appear allowing you to start again. I have put the new text
bestTimeTxt = new Text("Best Time: " + bestTime , "30px Monospace", "#000");
bestTimeTxt.textBaseLine = "top";
bestTimeTxt.x = 500;
bestTimeTxt.y = 100;
outside of the init() function so it shouldn't keep resetting I'm not sure what I am supposed to do as every combination i could think of isn't working.
here is my full code.
I'm also using easeljs for this game
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_value = 255;
var gray = Graphics.getRGB(20, 20, 20);
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var bestTime = 0;
var bestTimeTxt;
var matchesFoundText;
var squares;
var startingTime;
bestTimeTxt = new Text("Best Time: " + bestTime , "30px Monospace", "#000");
bestTimeTxt.textBaseLine = "top";
bestTimeTxt.x = 500;
bestTimeTxt.y = 100;
function init() {
var rows = 5;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
var numberOfTiles = rows*columns;
matchesFound = 0;
timeAllowable = 500;
startingTime = timeAllowable;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top"; // draw text relative to the top of the em box.
txt.x = 500;
txt.y = 0;
stage.addChild(bestTimeTxt);
stage.addChild(txt);
squares = [];
totalMatchesPossible = numberOfTiles/2;
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
matchesFoundText = new Text("Pairs Found: "+matchesFound+"/"+totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top"; // draw text relative to the top of the em box.
matchesFoundText.x = 500;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if (i % 2 === 0){
var color = randomColor();
}
var square = drawSquare(gray);
square.color = color;
square.x = (squareSide+squarePadding) * (placement % columns);
square.y = (squareSide+squarePadding) * Math.floor(placement / columns);
squares.push(square);
stage.addChild(square);
square.cache(0, 0, squareSide + squarePadding, squareSide + squarePadding);
square.onPress = handleOnPress;
stage.update();
};
}
function drawSquare(color) {
var shape = new Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*255);
var color2 = Math.floor(Math.random()*255);
var color3 = Math.floor(Math.random()*255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles){
for(var i = 0;i< numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
tile.graphics.beginFill(tile.color).rect(squareOutline, squareOutline, squareSide, squareSide);
if(!!tileClicked === false || tileClicked === tile){
tileClicked = tile;
tileClicked.updateCache("source-overlay");
}else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = "Pairs Found: "+matchesFound+"/"+totalMatchesPossible;
if (matchesFound===totalMatchesPossible){
gameOver(true);
}
}else{
tileClicked.graphics.beginFill(gray).rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked.updateCache("source-overlay");
tile.updateCache("source-overlay");
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable-Ticker.getTime()/1000));
txt.text = secondsLeft;
;
if (secondsLeft <= 0){
gameOver(false);
}
stage.update();
}
function gameOver(win){
Ticker.setPaused(true);
for(var i=0;i<squares.length;i++){
squares[i].graphics.beginFill(squares[i].color).rect(5, 5, 70, 70);
squares[i].onPress = null;
if (win === false){
squares[i].uncache();
}
}
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
if (win === true){
matchesFoundText.text = "You win!"
if((startingTime - secondsLeft) > bestTime)
{
bestTime = startingTime - secondsLeft;
bestTimeTxt.text = "Best Time: " + bestTime;
}
}
else
{
txt.text = secondsLeft + "... Game Over";
}
}
function replay(){
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
In your code, inside gameover method, I see you are using history.go(0) on play again link.
Technically, history.go(0) means to refresh the page and all your variables no matter the scope are set to the initial values.
If you want to retain the best score for the session and continue, use the replay method instead of history.
Updated Code :
replayParagraph.innerHTML = "<a href='#' onClick='replay();'>Play Again?</a>";

Categories