I'm having an issue here in my code that is driving me nuts. I have all my code and variables declared in an external .js file and I'm trying to print them out into an table which will be created in Javascript. Here is the external .js file and the HTML which references it.
loadImage.js
var pos = [];
var xAvg;
var yAvg;
var cirCtr;
var radAvg;
var defAvg;
var comPer;
var img=new Image();
img.onload=function(){
var can = document.getElementById('C');
var ctx = can.getContext('2d'); //creates canvas and image data
ctx.drawImage(img, 0, 0);
var imgdata = ctx.getImageData(0,0, img.width, img.height);
var data = imgdata.data;
var index = [];
var vertical;
var horizontal;
for (var i = 0; i < data.length; i += 4) {
if (data[i] == 255) { //finds position of piexel in data array
index.push(i);
}
}
for (var i = 0; i < index.length; i++) { //finds coordinate postion of pixel
var vertical =
Math.floor((index[i] / 4) / 400);
var horizontal =
Math.floor((index[i] / 4) % 400);
pos.push(horizontal, vertical);
}
var xTot = 0;
var yTot = 0;
for (var i = 0; i < pos.length; i+=2){
xTot = xTot + pos[i]; //finds x value of circe center
xAvg = xTot/( (pos.length+1) / 2);
};
for (var j = 1; j < pos.length; j+=2){
yTot = yTot + pos[j]; //finds y value of circle center
yAvg = yTot/( (pos.length+1) / 2);
};
cirCtr = [xAvg, yAvg];
alert("The center of the circle is " + cirCtr);
var radTot = 0;
//finds average radius of traced circle
for (var i = 0; i < pos.length; i+=2){
radTot = radTot + Math.sqrt(Math.pow((pos[i+1] - cirCtr[1]), 2) + Math.pow((pos[i] - cirCtr[0]), 2));
radAvg = radTot / ( (pos.length+1) / 2);
}
var defTot = 0;
for (var i = 0; i < pos.length; i+=2) {
defTot = defTot + (Math.abs(Math.sqrt(Math.pow((pos[i+1] - cirCtr[1]), 2) + Math.pow((pos[i] - cirCtr[0]), 2)) - radAvg));
defAvg = defTot / ( (pos.length+1) / 2);
}
comPer= 100 * ((Math.PI * Math.pow(radAvg,2))/(Math.PI * Math.pow((radAvg + defAvg), 2)));
alert(defTot);
alert("The radius of the circle is " + radAvg);
}
img.crossOrigin="anonymous"; //this had to do with the DOM Exception 18 thing
img.src="https://dl.dropboxusercontent.com/u/196150873/tile_0000_session_23220.skl.png";
the HTML
<html>
<head>
<script src="loadImage.js" type="text/javascript"></script>
<script> function();</script>
</head>
<body>
<h1>200 Circles</h1>
<canvas id="C" height="400" width="400"></canvas>
<div>
<table border="1">
<thead>
<tr>
<th>Center</th>
<th>Regular Radius</th>
<th>Derived Radius</th>
<th>Area proportionality</th>
</tr>
</thead>
<tbody id="log"></tbody>
</table>
</div>
<script>
for (var i=0; i < 10; i++) {
addRow();
}
function addRow() {
var newRow =
"<tr>" +
"<td>" + cirCtr + "</td>" +
"<td>" + radAvg + "</td>" +
"<td>" + (radAvg + defAvg) + "</td>" +
"<td>" + comPer + "</td>" +
"</tr>";
document.getElementById("log").innerHTML += newRow;
}
</script>
<body>
</html>
The issue us that the .js file is not loaded yet, when you
are referencing these variables.
I would use jquery ready event - http://api.jquery.com/ready/
If you can't use jquery, then see answers for this question - $(document).ready equivalent without jQuery
Another option is to keep both scripts on the same place, either in js file or in html.
Related
I would like to apply same piece of code to two objects in JavaScript.
When calling getElementsByClass ,there appears 2 objects in my website.So I would like to apply the same code for both of them.Currently I'm applying it to only one Object (text[0]) and I would like to implement it also to text[1] .
var text=document.getElementsByClassName("th");
var text =text[0];
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
I think you want to do the same thing with using item[0] and item[1] together.
You can create a function. Or call this function by iterating your items too.
var text=document.getElementsByClassName("th");
function myFunc(text) {
var newDom = '';
var animationDelay = 6;
for(let i = 0; i < text.innerText.length; i++)
{
newDom += '<span class="char">' + (text.innerText[i] == ' ' ? ' ' : text.innerText[i])+ '</span>';
}
text.innerHTML = newDom;
var length = text.children.length;
for(let i = 0; i < length; i++)
{
text.children[i].style['animation-delay'] = animationDelay * i + 'ms';
}
}
}
myFunc(text[0]); // call functions with your items.
myFunc(text[1]);
As I am new to JavaScript, I am a bit confused of using the for loops in JavaScript. I have tried the times table using the below JavaScript code, but I was unsuccessful in creating the times table for 1 to 9, as displayed in the image.
var display = ""; // The table output HTML
for (i = 1; i <= 9; i++) {
var multiplier = 1;
var result = i * 1;
display += multiplier + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
document.getElementById("outputDiv").innerHTML = display;
I tried using nested for loops, but it left me with an error
This is where I have done with a single for loop
https://codepen.io/vbudithi/pen/LgEPwx
I tried to get the output in the below form
THANKS IN ADVANCE
Use nested loop with break line. "< br >"
Working example: https://codepen.io/anon/pen/yRyLje
var display = "";
for( i = 1; i < 10; i++){
for (j = i; j < 10; j++) {
display += i + " * " + j + " = " + j * i+ "\xa0\xa0\xa0\xa0\xa0" ;
}
display +="<br>";
}
document.getElementById("outputDiv").innerHTML = display;
just like NicolasB said, wrapping the loop in another loop
var display = ""; // The table output HTML
for(j = 1; j <= 9; j++) {
for (i = j; i <= 9; i++) {
var result = i * j;
display += j + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
display += "<br>";
}
document.getElementById("outputDiv").innerHTML = display;
http://jsfiddle.net/tovic/AbpRD/
Fiddle has JavaScript, HTML, CSS
When code is placed in web page and rendered it does not
behave as the fiddle does (i.e. no line numbers)
(function () {
var pre = document.getElementsByTagName('pre'),
pl = pre.length;
for (var i = 0; i < pl; i++) {
pre[i].innerHTML = '<span class="line-number"></span>' + pre[i].innerHTML + '<span class="cl"></span>';
var num = pre[i].innerHTML.split(/\n/).length;
for (var j = 0; j < num; j++) {
var line_num = pre[i].getElementsByTagName('span')[0];
line_num.innerHTML += '<span>' + (j + 1) + '</span>';
}
}
})();
I'm relatively new to Javascript and i'm trying to generate multiple canvas elements on the same page to use as a "rating" display for products. (My javascript draws a number of stars)
This works fine when a product search results only returns one product (canvas element) however when there are multiple products, the canvas elements don't even appear on the page or the HTML itself.
Heres my code (I use AJAX search but i've stripped out most of it for readability, sorry if theres any syntax errors):
Search.js
function doRatings(avgRating, results){
/* Print search */
var canvas = new Array();
resultsHTML = '';
for(i=0;i<results.length;i++){
resultsHTML = resultsHTML + '<div id="AvgRating' + i + '"></div> <p>Under canvas</p>';
}
document.getElementById("content").innerHTML = '<div class="section group">' + resultsHTML + '</div>';
if(avgRating > 0){
canvas[i] = document.createElement('canvas');
canvas[i].width = 240;
canvas[i].height = 20;
canvas[i].id = i;
drawRating(canvas[i], avgRating);
document.getElementById("AvgRating" + i).appendChild(canvas[i]);
}
}
DrawStars.js
function drawRating(canvas, avgRating){
var ctx = canvas.getContext('2d');
//Start star loop
for(var s=0; s<avgRating; s++){
ctx.fillStyle = 'yellow';
ctx.stokeStyle = 'black';
//Work out the angles between each vertex
var a = (2 * Math.PI) / 10; //5 inside and outside angles
var radius = 10; //Determins the size of the stars
//Determine the positioning to draw the start based upon the interation of the loop and the size of the star
var starXY = [((s*(radius * 2 + 4)) + radius), radius];
ctx.beginPath();
//Begin drawing loop for star
for(var i = 11; i != 0; i--){
var r = radius*(i % 2 + 1) / 2;
var o = a * i;
ctx.lineTo((r * Math.sin(o)) + starXY[0], (r * Math.cos(o)) + starXY[1]);
}
ctx.closePath();
ctx.stroke();
ctx.fill();
}}
Adding loop to the canvas creation completes process - see fiddle
function doRatings(avgRating, results){
/* Print search */
var canvas = new Array();
resultsHTML = '';
for(i=0;i<results.length;i++){
resultsHTML = resultsHTML + '<div id="AvgRating' + i + '"></div> <p>Under canvas</p>';
}
document.getElementById("content").innerHTML = '<div class="section group">' + resultsHTML + '</div>';
for(i=0;i<results.length;i++){
if(avgRating > 0){
canvas[i] = document.createElement('canvas');
canvas[i].width = 240;
canvas[i].height = 20;
canvas[i].id = i;
drawRating(canvas[i], avgRating);
document.getElementById("AvgRating" + i).appendChild(canvas[i]);
}
}
}
I have implemented the Game of Life in Javascript. I am thinking about making a combobox which a listof colors to choose from. From there I want to render the obj.innerHTML img source of my grid cells in the game. What would be the best way to go about this?
Here is my code so far for the game:
<br>
<canvas id="canvas" width="100%" height="80%"></canvas>
<button onClick="generateLevel()">Create New Board</button>
<button onClick="step()">Step</button>
<button onClick="multiStep()">Multistep</button>
<script type="text/javascript">
var level;
var lastLevelDrawn;
var lvlWidth = 0;
var lvlHeight = 0;
function step()
{
var tempLevel = new Array(lvlHeight);
for (var y = 0; y < lvlHeight; y++)
{
tempLevel[y] = new Array(lvlWidth);
for (var x = 0; x < lvlWidth; x++)
{
var liveNeighborCount = 0;
var status = level[y][x];
for (var k = y-1; k < y+2; k++)
{
for (var j = x-1; j < x+2; j++)
{
if (k == y && j == x)
{
}
else if (k >= 0 && k < lvlHeight && j >= 0 && j < lvlWidth)
{
if (level[k][j] == "1")
{
liveNeighborCount++;
}
}
}
}
if (level[y][x] == "1")
{
if (liveNeighborCount != 2 && liveNeighborCount != 3)
{
status = "0";
}
}
if (level[y][x] == "0")
{
if (liveNeighborCount == 3)
{
status = "1";
}
}
tempLevel[y][x] = status;
}
}
level = tempLevel;
render();
}
function multiStep()
{
var steps = prompt("How many steps do you want to step?", "10");
for (var x = 0; x < steps; x++)
step();
}
function generateLevel()
{
var width = prompt("How many cells wide?", "10");
var height = prompt("How many cells high?", "10");
lvlWidth = width;
lvlHeight = height;
var output = "";
if (width != null && height != null)
{
level = new Array(lvlHeight);
lastLevelDrawn = new Array(lvlHeight);
for (var y = 0; y < height; y++)
{
level[y] = new Array(lvlWidth);
lastLevelDrawn[y] = new Array(lvlWidth);
for (var x = 0; x < width; x++)
{
level[y][x] = Math.floor((Math.random()*2));
lastLevelDrawn[y][x] = -1;
output += " " + level[y][x];
}
output += "<br>";
}
}
//document.getElementById("demo").innerHTML=output;
setupRender();
}
function changeTile(tile)
{
var x = tile % lvlWidth;
var y = parseInt(tile/lvlWidth);
//document.getElementById("demo").innerHTML=x + ":" + y;
if (level[y][x] == "1")
level[y][x] = "0";
else
level[y][x] = "1";
render();
}
function render()
{
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
for (var y = 0; y < lvlHeight; y++)
{
for (var z = 0; z < lvlWidth; z++)
{
var send = y*lvlWidth + z;
if (lastLevelDrawn[y][z] != level[y][z])
{
lastLevelDrawn[y][z] = level[y][z];
var obj = document.getElementById(send);
if (level[y][z] == "1")
obj.innerHTML = "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
obj.innerHTML = "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
}
}
}
}
function setupRender()
{
var x = "";
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
//x += "<table border='1' col width='((1/lvlWidth)*100)%' col height='((1/lvlHeight)*80)%'>";
for (var y = 0; y < lvlHeight; y++)
{
//x += "<tr>";
for (var z = 0; z < lvlWidth; z++)
{
lastLevelDrawn[y][z] = level[y][z];
//x += level[y][z];
var send = y*lvlWidth + z;
x += "<n id='" + send + "'>";
if (level[y][z] == "1")
x += "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
x += "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
x += "</n>";
}
x += "<br>";
//x += "</tr>";
}
//x += "</table>";
document.getElementById("demo").innerHTML=x;
}
</script>