I can't access my javascript code because of infinite prompts [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed last year.
Improve this question
Help, I've been using this website called "codepen" to do some javascript coding. But I accidently made it send me infinite prompts, everytime I open the project. Now I can't access the code. I searched for some time for an answer but I found none. heres a link to the problem: https://codepen.io/Aibel-Roy/pen/zYPBeEW
//I can't post the code because of the infinite prompts. Sorry.

Here's your code:
//config
var tick = 50;
var fieldOfView = 25;
var Speed = 0.25;
var ZMulti = 4;
var ClearOnDraw = true;
// variables
var keymap = [];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var meshA = [
"0,0,0",
"1,0,0",
"1,1,0",
"0,1,0",
"0,0,1",
"1,0,1",
"0,1,1",
"1,1,1"
];
var textures = [
"http://www.textures4photoshop.com/tex/thumbs/red-sofa-leather-seamless-texture-53.jpg"
];
var cameraData = [0, 0, 0];
//keymap
window.addEventListener(
"keydown",
(event) => {
var name = event.key;
keymap.push(name);
},
false
);
window.addEventListener(
"keyup",
(event) => {
var name = event.key;
if (keymap.includes(name)) {
keymap.splice(keymap.indexOf(name), 1);
}
},
false
);
//render img
function draw() {
if (ClearOnDraw) {
ctx.clearRect(0, 0, 10000, 1000);
}
var img = new Image(); // texturing
img.src = textures[0];
prompt(img.src);
img.onLoad = function () {
var pattern = context.createPattern(imageObj, "repeat");
ctx.fillStyle = pattern;
var prevVert;
for (let i = 0; i <= meshA.length; i++) {
//convert 3D vector to 2D
var vert = meshA[i];
if (i >= meshA.length) {
vert = meshA[0];
}
var vertPos = vert.split(",");
var zMag = (vertPos[2] - cameraData[2]) * (fieldOfView / ZMulti);
var vertPos2D = [
(vertPos[0] - cameraData[0]) * fieldOfView + zMag,
(vertPos[1] - cameraData[1]) * fieldOfView + zMag
];
ctx.beginPath();
ctx.moveTo(vertPos2D[0], vertPos2D[1]);
for (let i1 = 0; i1 < meshA.length; i1++) {
var prv = meshA[i1].split(",");
var PrevzMag = (prv[2] - cameraData[2]) * (fieldOfView / ZMulti);
var I1VertPos = [
(prv[0] - cameraData[0]) * fieldOfView + PrevzMag,
(prv[1] - cameraData[1]) * fieldOfView + PrevzMag
];
ctx.lineTo(I1VertPos[0], I1VertPos[1]);
ctx.stroke();
}
ctx.closePath();
ctx.fill();
prevVert = vertPos2D;
}
};
}
function Movement() {
if (keymap.includes("w")) {
cameraData[2] -= Speed * 2;
}
if (keymap.includes("s")) {
cameraData[2] += Speed * 2;
}
if (keymap.includes("d")) {
cameraData[0] -= Speed;
}
if (keymap.includes("a")) {
cameraData[0] += Speed;
}
}
draw();
setInterval(function main() {
draw();
Movement();
}, tick);
How to disable the prompt(if the browser doesn't suggest you to suppress it):
On that page, bring up dev tools(Command + Option + I, or F12 on Windows).
Choose the correct page on the dev tool, usually looks like CodePen (Hash ID)
Override the prompt function in the console by typing window.prompt = () => {}.
Change your code, save and refresh the page.
There are probably better ways to do it but disabling JavaScript makes the code section unusable.

In your function draw(), there is a prompt in here:
function draw() {
// Trimmed
prompt(img.src);
// Trimmed
}
You also have setInterval calling draw() at a particular interval defined in tick (where you have assigned 50ms as the value):
setInterval(function main() {
draw();
Movement();
}, tick);
As a result, draw() gets called every 50ms, where prompt(img.src) gets called, leading to infinite prompt.
You need to change whatever you are doing in setInterval().

Related

html canvas element blinking and then bugging out

I'm trying to have asteroids moving across the screen for a game. The first few asteroids work and then each asteroid will start blinking and bugging out to the point where they won't move across the screen. The variables acx and acy are the x and y coordinates for the asteroids respectively.
setInterval(throwAsteroid1A, 5000);
function throwAsteroid1A() {
var asteroidCanvas = document.getElementById('asteroidCanvas');
var context = asteroidCanvas.getContext('2d');
var acx = Math.floor(Math.random() * 200);
var acy = Math.floor(Math.random() * 10);
setInterval( () => {
asteroid.onload = function() {
context.drawImage(asteroid, asx, asy, aswidth, asheight, acx, acy, 20, 20);
acx += 1;
acy += 1;
}
asteroid.src = 'https://i.imgur.com/WfQKE6T.png';
}, 10)
setInterval(asteroidPath, 50)
}
function asteroidPath() {
// let computedStyle = getComputedStyle(canvasDisplay)
var asteroidCanvas = document.getElementById('asteroidCanvas');
let ctx = asteroidCanvas.getContext("2d");
ctx.clearRect(acx,acy, canvasDisplay.width, canvasDisplay.height);
}
Well there's obviously something conceptually wrong with your approach. I think the blinking is caused by a timing issue in-between the numerous individual interval timers you set up. The callback function asteroidPath() clears a part of the canvas and this might happen at the same time a new Asteroid has been added to the screen - which will delete it either entirely or partly depending on it's screen position.
To work around it you should:
keep a list of all asteroid objects
clear the screen completely once
update all asteroid's at once - not each one with it's own timer
So an example based on your code might look a little something like this (just click 'Run code snippet'):
Asteroid = function() {
this.acx = Math.floor(Math.random() * 200);
this.acy = Math.floor(Math.random() * 10);
this.image = new Image();
this.image.onload = function(e) {
this.loaded = true;
this.aswidth = e.target.naturalWidth;
this.asheight = e.target.naturalHeight;
}
this.image.src = 'https://i.imgur.com/WfQKE6T.png';
}
var asteroidCanvas = document.getElementById('asteroidCanvas');
var context = asteroidCanvas.getContext('2d');
let asteroids = [];
function spawnAsteroid() {
asteroids.push(new Asteroid());
}
function updateCanvas() {
context.clearRect(0, 0, asteroidCanvas.width, asteroidCanvas.height);
let asteroid;
for (let a = 0; a < asteroids.length; a++) {
asteroid = asteroids[a];
if (asteroid.image.loaded) {
context.drawImage(asteroid.image, 0, 0, asteroid.image.aswidth, asteroid.image.asheight, asteroid.acx, asteroid.acy, 20, 20);
asteroid.acx += 1;
asteroid.acy += 1;
}
}
}
setInterval(spawnAsteroid, 2000);
setInterval(updateCanvas, 50);
spawnAsteroid();
<canvas id="asteroidCanvas"></canvas>

HTML Canvas in for loop only displaying after loop completes

I'm having a bit of trouble making a progress graph. This is my first time using canvas so I'm a little new to the concept. This page is going to be a little prime number benchmark for an assignment at school. I haven't done the algorithm yet so right now that just counts up. I wanted to have a graph display the progress of the benchmark to the user so it doesn't look like the page has just frozen. I've broken the benchmark down into "sprints", where the device will calculate numbers for a set period of time and then update the graph. Problem is, the graph doesn't seem to update until the end of the "benchmark". Any recommendations?
The javascript is below (execBench is probably the most relevant function):
function startBench() {
// move to benchmark display
//showPage("bench");
jQuery.mobile.changePage("#bench");
setTimeout(
function () {
// run benchmark
var score = execBench(10);
//set score and move page
$(".result").text(score);
setTimeout(function () {
showPage("result");
}, 4000);
}, 2000);
}
function debugmsg(message) {
console.log(message);
}
function execBench(time) {
var graphUpdateRate = 2; // horizontal "resolution" of graph/sprint length in s
var sprintCount = Math.floor(time / graphUpdateRate);
debugmsg("Running " + sprintCount + " " + graphUpdateRate + "-second sprints");
var currentTime = new Date();
var sprintDeadline = currentTime;
var counter = 0; // "score" for the end, # of primes generated
var lastPrime = 0;
var record = []; // datapoints for graph
for (var i = 0; i < sprintCount; i++) {
// perform calculations
sprintDeadline = incrementDate(new Date(), graphUpdateRate);
while (currentTime < sprintDeadline) {
currentTime = Date.now();
lastPrime = generatePrime(lastPrime);
counter++;
}
// report progress
record.push(counter);
drawGraph(document.getElementById('progGraph'), record, sprintCount);
}
return counter;
}
function generatePrime(min) {
//placeholder for algorithm
min++;
return min;
}
function drawGraph(canvas, dataPoints, maxPoints) {
var context = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
var xIncrement = width / maxPoints;
var xBegin = 0;
var prevPoint = 0;
var yScale = -1 * height / Math.max(...dataPoints);
//reset canvas
canvas.width = canvas.width;
context.clearRect(0, 0, canvas.width, canvas.height);
//move context to bottom right and set scale
context.translate(0, height);
context.scale(1, 1);
context.strokeStyle = "#ed1e79";
for (dataPoint in dataPoints) {
currentPoint = (dataPoints[dataPoint] * yScale);
context.beginPath();
context.moveTo(xBegin, prevPoint);
context.lineTo(xBegin + xIncrement, currentPoint);
context.lineWidth = 3;
context.lineCap = 'round';
context.stroke();
prevPoint = currentPoint;
xBegin += xIncrement;
}
debugmsg(Math.max(...dataPoints));
return;
}
function incrementDate(date, seconds) {
return new Date(date.getTime() + (seconds * 1000));
}
As an example of using requestAnimationFrame(), you could try something like this.
function execBench(time) {
var graphUpdateRate = 2; // horizontal "resolution" of graph/sprint length in s
var sprintCount = Math.floor(time / graphUpdateRate);
debugmsg("Running " + sprintCount + " " + graphUpdateRate + "-second sprints");
var currentTime = new Date();
var sprintDeadline = currentTime;
var counter = 0; // "score" for the end, # of primes generated
var lastPrime = 0;
var record = []; // datapoints for graph
var i = 0;
(function drawSprint() {
// perform calculations
sprintDeadline = incrementDate(new Date(), graphUpdateRate);
while (currentTime < sprintDeadline) {
currentTime = Date.now();
lastPrime = generatePrime(lastPrime);
counter++;
}
// report progress
record.push(counter);
drawGraph(document.getElementById('progGraph'), record, sprintCount);
i++;
if (i < sprintCount) {
requestAnimationFrame(drawSprint);
}
})();
return counter;
}
Your while loop is "blocking". It eats up CPU, not allowing javascript and probably much else on the computer to do anything.
Instead, use setTimeout(fn, t) to schedule the next update.
setTimeout() is non blocking. Its fn will execute in a fresh event thread in t milliseonds time (or shortly thereafter).
Between setTimouts, your computer's processor will have the capacity to instruct the graphich card to render the canvas.

Creating an javascript graph with marker that is synchronize with a movie

I'm trying to create an online web tool for eeg signal analysis. The tool suppose to display a graph of an eeg signal synchronize with a movie that was display to a subject.
I've already implemented it successfully on csharp but I can't find a way to do it easily with any of the know javascript chart that I saw.
A link of a good tool that do something similar can be found here:
http://www.mesta-automation.com/real-time-line-charts-with-wpf-and-dynamic-data-display/
I've tried using dygraph, and google chart. I know that it should be relatively easy to create an background thread on the server that examine the movie state every ~50ms. What I was not able to do is to create a marker of the movie position on the chart itself dynamically. I was able to draw on the dygraph but was not able to change the marker location.
just for clarification, I need to draw a vertical line as a marker.
I'm in great suffering. Please help :)
Thanks to Danvk I figure out how to do it.
Below is a jsfiddler links that demonstrate such a solution.
http://jsfiddle.net/ng9vy8mb/10/embedded/result/
below is the javascript code that do the task. It changes the location of the marker in synchronizing with the video.
There are still several improvement that can be done.
Currently, if the user had zoomed in the graph and then click on it, the zoom will be reset.
there is no support for you tube movies
I hope that soon I can post a more complete solution that will also enable user to upload the graph data and video from their computer
;
var dc;
var g;
var v;
var my_graph;
var my_area;
var current_time = 0;
//when the document is done loading, intialie the video events listeners
$(document).ready(function () {
v = document.getElementsByTagName('video')[0];
v.onseeking = function () {
current_time = v.currentTime * 1000;
draw_marker();
};
v.oncanplay = function () {
CreateGraph();
};
v.addEventListener('timeupdate', function (event) {
var t = document.getElementById('time');
t.innerHTML = v.currentTime;
g.updateOptions({
isZoomedIgnoreProgrammaticZoom: true
});
current_time = v.currentTime * 1000;
}, false);
});
function change_movie_position(e, x, points) {
v.currentTime = x / 1000;
}
function draw_marker() {
dc.fillStyle = "rgba(255, 0, 0, 0.5)";
var left = my_graph.toDomCoords(current_time, 0)[0] - 2;
var right = my_graph.toDomCoords(current_time + 2, 0)[0] + 2;
dc.fillRect(left, my_area.y, right - left, my_area.h);
};
//data creation
function CreateGraph() {
number_of_samples = v.duration * 1000;
// A basic sinusoidal data series.
var data = [];
for (var i = 0; i < number_of_samples; i++) {
var base = 10 * Math.sin(i / 90.0);
data.push([i, base, base + Math.sin(i / 2.0)]);
}
// Shift one portion out of line.
var highlight_start = 450;
var highlight_end = 500;
for (var i = highlight_start; i <= highlight_end; i++) {
data[i][2] += 5.0;
}
g = new Dygraph(
document.getElementById("div_g"),
data, {
labels: ['X', 'Est.', 'Actual'],
animatedZooms: true,
underlayCallback: function (canvas, area, g) {
dc = canvas;
my_area = area;
my_graph = g;
bottom_left = g.toDomCoords(0, 0);
top_right = g.toDomCoords(highlight_end, +20);
draw_marker();
}
});
g.updateOptions({
clickCallback: change_movie_position
}, true);
}

My javascript canvas map script and poor performance

Basically below is my script for a prototype which uses 128x128 tiles to draw a map on a canvas which user can drag to move around.
Script does work. However I have a few problems to be solved:
1. Poor performance and I can't figure out why.
2. I am missing a method to buffer the tiles before the actual drawing.
3. If you notice any other issues also that could help me to make things run more smoothly it would be fantastic.
Some explanations for the script:
variables
coordinates - Defines the actual images to be displayed. Image file names are type of '0_1.jpg', where 0 is Y and 1 is X.
mouse_position - As name says, is keeping record of mouse position.
position - This is a poorly named variable. It defines the position of the context drawn on canvas. This changes when user drags the view.
Any assistance would be appreciated greatly. Thank you.
var coordinates = [0, 0];
var mouse_position = [0, 0];
var position = [-128, -128];
var canvas = document.getElementById('map_canvas');
var context = canvas.getContext('2d');
var buffer = [];
var buffer_x = Math.floor(window.innerWidth/128)+4;
var buffer_y = Math.floor(window.innerHeight/128)+4;
var animation_frame_request = function() {
var a = window.requestAnimationFrame;
var b = window.webkitRequestAnimationFrame;
var c = window.mozRequestAnimationFrame;
var d = function(callback) {
window.setTimeout(callback, 1000/60);
}
return a || b || c || d;
}
var resizeCanvas = function() {
window.canvas.width = window.innerWidth;
window.canvas.height = window.innerHeight;
window.buffer_x = Math.floor(window.innerWidth/128)+4;
window.buffer_y = Math.floor(window.innerHeight/128)+4;
window.buffer = [];
for (row = 0; row < window.buffer_y; row++) {
x = [];
for (col = 0; col < window.buffer_x; col++) {
x.push(new Image());
}
window.buffer.push(x);
}
}
var render = function() {
animation_frame_request(render);
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
cy = window.coordinates[1]+row;
cx = window.coordinates[0]+col;
window.buffer[row][col].src = 'map/'+cy+'_'+cx+'.jpg';
}
}
for (row = 0; row < window.buffer_y; row++) {
for (col = 0; col < window.buffer_x; col++) {
window.context.drawImage(window.buffer[row][col],
window.position[0]+col*128,
window.position[1]+row*128, 128, 128);
}
}
}
var events = function() {
window.canvas.onmousemove = function(e) {
if (e['buttons'] == 1) {
window.position[0] += (e.clientX-window.mouse_position[0]);
window.position[1] += (e.clientY-window.mouse_position[1]);
if (window.position[0] >= 0) {
window.position[0] = -128;
window.coordinates[0] -= 1;
} else if (window.position[0] < -128) {
window.position[0] = 0;
window.coordinates[0] += 1;
}
if (window.position[1] >= 0) {
window.position[1] = -128;
window.coordinates[1] -= 1;
} else if (window.position[1] < -128) {
window.position[1] = 0;
window.coordinates[1] += 1;
}
render();
}
window.mouse_position[0] = e.clientX;
window.mouse_position[1] = e.clientY;
}
}
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('load', resizeCanvas, false);
window.addEventListener('mousemove', events, false);
resizeCanvas();
To get better performance you should avoid changing the src of img nodes and move them around instead.
A simple way to minimize the number of img nodes handled and modified (except for screen positioning) is to use an LRU (Least Recently Used) cache.
Basically you keep a cache of last say 100 image nodes (they must be enough to cover at least one screen) by using a dictionary mapping the src url to a node object and also keeping them all in a doubly-linked list.
When a tile is required you first check in the cache, and if it's already there just move it to the front of LRU list and move the img coordinates, otherwise create a new node and set the source or, if you already hit the cache limit, reuse the last node in the doubly-linked list instead. In code:
function setTile(x, y, src) {
var t = cache[src];
if (!t) {
if (cache_count == MAXCACHE) {
t = lru_last;
t.prev.next = null;
lru_last = t.prev;
t.prev = t.next = null;
delete cache[t.src]
t.src = src;
t.img.src = src;
cache[t.src] = t;
} else {
t = { prev: null,
next: null,
img: document.createElement("img") };
t.src = src;
t.img.src = src;
t.img.className = "tile";
scr.appendChild(t.img);
cache[t.src] = t;
cache_count += 1;
}
} else {
if (t.prev) t.prev.next = t.next; else lru_first = t.next;
if (t.next) t.next.prev = t.prev; else lru_last = t.prev;
}
t.prev = null; t.next = lru_first;
if (t.next) t.next.prev = t; else lru_last = t;
lru_first = t;
t.img.style.left = x + "px";
t.img.style.top = y + "px";
scr.appendChild(t.img);
}
I'm also always appending the requested tile to the container so that it goes in front of all other existing tiles; this way I don't need to remove old tiles and they're simply left behind.
To update the screen I just iterate over all the tiles I need and request them:
function setView(x0, y0) {
var w = scr.offsetWidth;
var h = scr.offsetHeight;
var iy0 = y0 >> 7;
var ix0 = x0 >> 7;
for (var y=iy0; y*128 < y0+h; y++) {
for (var x=ix0; x*128 < x0+w; x++) {
setTile(x*128-x0, y*128-y0, "tile_" + y + "_" + x + ".jpg");
}
}
}
most of the time the setTile request will just update the x and y coordinates of an existing img tag, without changing anything else. At the same time no more than MAXCACHE image nodes will be present on the screen.
You can see a full working example in
http://raksy.dyndns.org/tiles/tiles.html

For Loop MovieClip Grid not showing on stage

So I'm a newbie and should obviously spend time in the tuts, but I'm looking for a quick answer. Basically, I've created a grid of movie clips with AS3. When I 'preview' the flash (as a flash or HTML) it shows up fine. Success. Yet, the stage remains empty.
Q1) Will the stage remain empty as I have used AS3 to dynamically 'draw' the grid of mc's? Or is there a slit of code I am missing to make this baby show up on the stage?
Q2) I've managed to use alpha to make the MC's 'fade' on hover - but I want to make them change color (to red) when hovered over. I've searched everywhere and can't seem to find the right script.
Here is my code:
var stage = new createjs.Stage("canvas");
var image = new createjs.Bitmap("images/square.png");
stage.addChild(image);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
image.x += 10;
stage.update();
}
var x0:Number = 0;
var y0:Number = 0;
var nt:Number = 72;
var nc = 10;
var vd:Number = 12;
var hd:Number = 12;
for (var i = 1; i <= nt; i++) {
var mc = this.attachMovie("square", "square" + i, i);
var aprox = Math.floor((i - 1) / nc);
mc._x = x0 + hd * ((i - aprox * nc) - 1);
mc._y = y0 + aprox * vd;
mc.useHandCursor = true;
// fade in
mc.onRollOver = function()
{
this.onEnterFrame = function()
{
if (this._alpha > 0) {
this._alpha -= 10;
} else {
this._alpha = 0;
delete this.onEnterFrame;
}
};
};
// fade out
mc.onRollOut = function()
{
this.onEnterFrame = function()
{
if (this._alpha < 100) {
this._alpha += 10;
} else {
this._alpha = 100;
delete this.onEnterFrame;
}
};
};
}
Thanks in advance - sorry I am a noob.
This will never work. 1/3 of your code is in AS3, 2/3 in AS2. Considering you haven't been thrown any error, I assume you exported it as AS2.

Categories

Resources