I'm trying to use the distance formula to find the difference between two castle on a game. The game stores the castle coordinates in the following format
"l+k://coordinates?16321,16520&146" the coordinates of this castle would be 16321 & 16520. I have written a function to extract this information from two castle links and then use the distance formula to return the answer. However for some reason when this function is called in the website it does not return the expected result. Does anyone know why this might be happening. Please find my code below. I have also attached a JSFiddle.
https://jsfiddle.net/ajdxetod/
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Lords & Knights - Distance Calculator</title>
<script type="text/javascript" src="distanceScript.js"></script>
</head>
<body>
<h1 class="heading">Distance Calculator</h1>
<div>
<fieldset>
<legend>Castle Link One</legend>
<input type="text" id="castle_one">
</fieldset>
</div>
<div>
<fieldset>
<legend>Castle Link Two</legend>
<input type="text" id="castle_two">
</fieldset>
</div>
<div class="map_of_areadiv">
<fieldset>
<legend>Is Map Of Area Researched</legend>
<input type="checkbox" id="moa_checkbox" checked="true"><label for="moa_checkbox">Is "Map Of Area Researched in the Libary?</label>
</fieldset>
</div>
<div class="calculate_button">
<button id="calculate" onclick="distanceCastles()">Calculate Distance</button>
</div>
<div class="distance_output">
<fieldset id="castle_distance">
<legend>Distance (in fields)</legend>
<input type="text" id="output" placeholder="Click the Calculate Distance Button">
</fieldset>
<textarea id="troop_times"></textarea>
</div>
</body>
distanceScript.js
var castleone;
var castletwo;
var x1;
var x2;
var y1;
var y2;
var distance = 0;
function distanceCastles() {
castleone = document.getElementById("castle_one") ;
castletwo = document.getElementById("castle_two") ;
if (typeof castleone === "string" && castleone.length === 33) {
x1 = castleone.substring(18, 23);
y1 = castleone.substring(24, 29);
x2 = castletwo.substring(18, 23);
y2 = castletwo.substring(24, 29);
distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
document.getElementById("output").innerHTML = distance;
}
else if (typeof castleone !== "string" || castleone.length !== 33) {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
}
else {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
}
}
You are declaring a variable
var distance = 0;
And then you create a function with the same name
function distance () {
// code...
}
and you wonder why you get an error. Rename either.
Some issues
As what first answer stated the distance was declared as a variable first
You are comparing an html object with a string..You don't need to do this (See how I attempted it)
You are trying to insert out message without using using the property innerHTML OR textContent..
You can get the value of each input distance using .value property of input box
See snippet below
<!DOCTYPE html>
<html>
<head>
<title>Lords & Knights - Distance Calculator</title>
<script type="text/javascript" src="distanceScript.js"></script>
</head>
<body>
<script>
var castleone;
var castletwo;
var x1;
var x2;
var y1;
var y2;
function distance() {
castleone = document.getElementById("castle_one");
castletwo = document.getElementById("castle_two");
if (castleone.value.length === 33) {
x1 = castleone.value.substring(18, 23);
y1 = castleone.value.substring(24, 29);
x2 = castletwo.value.substring(18, 23);
y2 = castletwo.value.substring(24, 29);
distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
console.log(distance);
document.getElementById("output").value = distance;
} else if (castleone.value.length !== 33) {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
} else {
document.getElementById("troop_times").innerHTML = "Error: You have not entered valid castle links";
}
}
</script>
<h1 class="heading">Distance Calculator</h1>
<div>
<fieldset>
<legend>Castle Link One</legend>
<input type="text" id="castle_one">
</fieldset>
</div>
<div>
<fieldset>
<legend>Castle Link Two</legend>
<input type="text" id="castle_two">
</fieldset>
</div>
<div class="map_of_areadiv">
<fieldset>
<legend>Is Map Of Area Researched</legend>
<input type="checkbox" id="moa_checkbox" checked="true">
<label for="moa_checkbox">Is "Map Of Area Researched in the Libary?</label>
</fieldset>
</div>
<div class="calculate_button">
<button id="calculate" onclick="distance()">Calculate Distance</button>
</div>
<div class="distance_output">
<fieldset id="castle_distance">
<legend>Distance (in fields)</legend>
<input type="text" id="output" placehodler="Click the Calculate Distance Button">
</fieldset>
<textarea id="troop_times"></textarea>
</div>
</body>
</html>
Related
let y = document.getElementById("weathMeas").innerHTML;
function calc(y) {
var z;
z = (y * 1.8) + 32;
return z;
}
document.getElementById("demo").innerHTML = calc(y);
<head>
<section id="calcBody"> <span id="infomsg">Please enter current temperature :</span>
<p>
<input type="text" id="weathMeas" name="weather" value="58">
</p>
<input type="button" id="result" value="result!">
<p id="demo"></p>
</section>
</head>
Is this what you're looking for?
function calc() {
let y = document.getElementById("weathMeas").value;
let yInt = parseInt(y);
var z;
z = (yInt * 1.8) + 32;
document.getElementById("demo").innerHTML = z;
}
<head>
<section id="calcBody"> <span id="infomsg">Please enter current temperature :</span>
<p>
<input type="text" id="weathMeas" name="weather" value="58">
</p>
<input type="button" id="result" value="result!" onclick="calc()">
<p id="demo"></p>
</section>
</head>
I am using a canvas element to generate a base64 image of text. When I hit the "Generate text" button, the canvas populates with the image, but it doesn't resize until you hit the button a second time. (And weirdly, on my machine, my fonts don't work until the second click either)
My Fiddle is below, and you can see that the function works partially on the first click, and that's what's baffling me.
I have checked answers here, here, and here already, but I am not a jQuery expert, and I don't know how to apply some of these solutions to my specific case. I have tried some of the proposed solutions in the answers above including:
Wrapping my code in $(document).ready(function() {}
Using $("#addText").click instead of $("#addText").on("click"...
Edit: As mentioned by #Barmar in the comments, it resizes to about half on the first try. That's because the lineCount() function outputs the wrong number on the first click.
$(document).ready(function() {
$("#addText").click(txtimg);
$("#myDownload").click(function() {
var canvas = document.getElementById("myCanvas");
var fullQuality = canvas.toDataURL("image/png", 1.0);
$('#imgURL').val(fullQuality);
});
$("input[type='radio'][name='fontRadios']").click(function() {
console.log($("input[type='radio'][name='fontRadios']:checked").val());
});
$("#colorChooser > label").on("click", function() {
$('#colorPreview').css("background-color", $(this).attr('data-color')),
txtimg();
});
$("#CaptureURL").click(function() {
$("#imgURL").select();
document.execCommand('copy');
});
});
function txtimg() {
var fontSize = parseInt($('#fontSizeValue').html());
var fontColor = $('#colorChooser > label > input:checked').attr('id');
var fontFam = $("input[type='radio'][name='fontRadios']:checked").val();
var canvas = document.getElementById("myCanvas");
var myMessage = $("#myMessage").val();
var maxWidth = 600;
var lineHeight = parseInt($('#lineHeightValue').html());
var ctx = canvas.getContext("2d");
var canvHeight = lineHeight * lineCount(ctx, myMessage, maxWidth);
canvas.height = lineHeight * lineCount(ctx, myMessage, maxWidth);
var x = canvas.width / 2;
var y = canvas.height;
//ctx.clearRect(0, 0, canvas.width, canvas.height);
//ctx.beginPath();
//ctx.moveTo(x, 0);
ctx.font = fontSize + "px " + fontFam;
ctx.fillStyle = fontColor;
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
//ctx.fillText(myMessage, x, y);
wrapText(ctx, myMessage, x, 0 + lineHeight, maxWidth, lineHeight);
}
function lineCount(context, text, maxWidth) {
var words = text.split(' ');
var line = '';
var lines = 1;
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
line = words[n] + ' ';
lines++;
} else {
line = testLine;
}
}
return lines;
}
function wrapText(context, text, x, y, maxWidth, lineHeight) {
var words = text.split(' ');
var line = '';
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
}
function fontVal(elem) {
var fv = document.getElementById('fontSizeValue');
if (fv.innerHTML != elem.value) {
fv.innerHTML = elem.value;
console.log(elem.value);
}
}
function lineVal(elem) {
var lv = document.getElementById('lineHeightValue');
if (lv.innerHTML != elem.value) {
lv.innerHTML = elem.value;
console.log(elem.value);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Helloworld!</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.0/css/all.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Oswald|Roboto|Sofia" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="d-flex flex-row align-content-center mb-5">
<div class="d-flex align-self-center mx-auto">
<canvas id="myCanvas" width="600" height="100" style="border: 1px solid #cecece;"></canvas>
</div>
</div>
<form id="myForm">
<div class="form-group">
<label for="myMessage">Message</label>
<input type="text" name="myMessage" id="myMessage" class="form-control" value="Did you ever hear the tragedy of Darth Plagueis the Wise? I thought not. It's not a story the Jedi would tell you. It's a Sith legend. Darth Plagueis was a Dark Lord of the Sith, so powerful and so wise he could use the Force to influence the midichlorians to create life... He had such a knowledge of the dark side that he could even keep the ones he cared about from dying. The dark side of the Force is a pathway to many abilities some consider to be unnatural. He became so powerful... the only thing he was afraid of was losing his power, which eventually, of course, he did. Unfortunately, he taught his apprentice everything he knew, then his apprentice killed him in his sleep. It's ironic he could save others from death, but not himself."
/>
</div>
<hr/>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="fontRange">Font Size: </label><span id="fontSizeValue">32</span><span>px</span>
<input type="range" class="form-control-range" id="fontRange" min="8" max="128" value="32" onChange="fontVal(this)" onMouseMove="fontVal(this)">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="lineRange">Line Height</label><span id="lineHeightValue">32</span><span>px</span>
<input type="range" class="form-control-range" id="lineRange" min="0" max="128" value="32" onChange="lineVal(this)" onMouseMove="lineVal(this)">
</div>
</div>
</div>
<hr/>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label for="fontSizeSelect">Typeface</label>
<div class="form-check">
<input class="form-check-input" type="radio" name="fontRadios" id="Oswald" value="Oswald" checked>
<label class="form-check-label" for="WP">
Oswald
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="fontRadios" id="Roboto" value="Roboto">
<label class="form-check-label" for="TG">
Roboto
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="fontRadios" id="Sofia" value="Sofia">
<label class="form-check-label" for="TGB">
Sofia
</label>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="btn-group btn-group-toggle w-100" data-toggle="buttons" id="colorChooser">
<label class="btn rush-red active" data-color="#ed1c24">
<input type="radio" name="colorOptions" id="#ed1c24" autocomplete="off" checked>Red
</label>
<label class="btn rush-gold" data-color="#eeb111">
<input type="radio" name="colorOptions" id="#eeb111" autocomplete="off">Gold
</label>
<label class="btn rush-grey" data-color="#505051">
<input type="radio" name="colorOptions" id="#505051" autocomplete="off">Grey
</label>
<label class="btn rush-black" data-color="#111111">
<input type="radio" name="colorOptions" id="#111111" autocomplete="off">Black
</label>
</div>
<div class="card">
<div id="colorPreview" class="card-body" style="background-color: #ed1c24;">
</div>
</div>
</div>
</div>
<button id="addText" class="btn btn-primary" type="button">
Add Text
</button>
</form>
<hr/>
<button class="btn btn-primary" type="button" id="myDownload">
<i class="fa fa-code pr-2"></i>Generate Image URL
</button>
<button class="btn btn-primary" type="button" id="CaptureURL">
<i class="fa fa-copy pr-2"></i>Copy
</button>
<!--a class="btn disabled float-right" id="linkURL" href="#" target="_blank">
<i class="fa fa-external-link-alt pr-2"></i>Test in Browser
</a-->
<textarea id="imgURL" class="form-control"></textarea>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</body>
</html>
Set the canvas font properties before the first time you call lineCount(). The inner call to measureText() is using whatever defaults there are before you assign them.
I found the answer here:
Drawing text to <canvas> with #font-face does not work at the first time
Browsers load the font in the background, asynchronously, so I put them in the document elsewhere to be loaded. this was throwing off the measureText() function, and therefore throwing off the line spacing
I have been attempting to figure out how to create a distance calculator. I think the formula is correct, but my issue is that my variables will not run through the formula or even display in my output.
<!doctype html>
<!-- distance.html Mason Boroff -->
<!-- =================================================== -->
<html>
<head>
<title> Distance Calculator </title>
<script type="text/javascript">
function ShowDistance()
{
var x1, x2, y1, y2;
x1=parsefloat(document.getElementById('xOne').value);
x2=parsefloat(document.getElementById('xTwo').value);
y1=parsefloat(document.getElementById('yOne').value);
y2=parsefloat(document.getElementById('yTwo').value);
var distance = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-
y2), 2) );
return distance;
document.getElementById('outPut').innerHTML=
'The distance bewtween (' + x1 + ',' + y1 + ') and ('
+ x2 + ',' + y2 + ') is '+ distance +;
}
</script>
</head>
<body>
<h2>Distance Calculator</h2>
<p>
Coordinate 1: (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br>
Coordinate 2: (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<br>
<input type="button" onclick="ShowDistance()" value="Calculate
Distance";>
</p>
<hr>
<div id="outPut"> </div>
</body>
Posting the corrected code.
There is always a good way to debug your code when writing front end code. The browser. Learn how to use browser console.
<!doctype html>
<!-- distance.html Mason Boroff -->
<!-- =================================================== -->
<html>
<head>
<title> Distance Calculator </title>
<script type="text/javascript">
function ShowDistance()
{
var x1, x2, y1, y2;
x1=parseFloat(document.getElementById('xOne').value);
x2=parseFloat(document.getElementById('xTwo').value);
y1=parseFloat(document.getElementById('yOne').value);
y2=parseFloat(document.getElementById('yTwo').value);
var distance = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-
y2), 2) );
document.getElementById('outPut').innerHTML=
'The distance bewtween (' + x1 + ',' + y1 + ') and ('
+ x2 + ',' + y2 + ') is '+ distance ;
return distance;
}
</script>
</head>
<body>
<h2>Distance Calculator</h2>
<p>
Coordinate 1: (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br>
Coordinate 2: (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<br>
<input type="button" onclick="ShowDistance()" value="Calculate
Distance">
</p>
<hr>
<div id="outPut"> </div>
</body>
How I debugged it?
USe F12...then I looked into the console to check that there is an error in the line having extra +.
So I changed it.
Then I saw the complaign about parseFloat. Then I checked refernce to find out there is an method called parseFloat not parsefloat`.
Then I saw no outpout and no error. WHich made me check code again which revealed that there is return statement before you assign the result to innerHTML...
That's how I debugged it.
You should learn :-
How to use chrome debugger.
Checking the manual when you get stuck or in doubt about built in functions.
Learn a bit more javascript and basi control flow of programs.
There are several typos/syntax related issues in the code as well as a return in the function that prevents the printing line to be reached.
You have parsefloat calling while the function name is parseFloat. There also is a concat operator that does not have anything to follow distance +.
Here is an update snippet:
function ShowDistance()
{
var x1, x2, y1, y2;
x1=parseFloat(document.getElementById('xOne').value);
x2=parseFloat(document.getElementById('xTwo').value);
y1=parseFloat(document.getElementById('yOne').value);
y2=parseFloat(document.getElementById('yTwo').value);
var distance = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-
y2), 2) );
document.getElementById('outPut').innerHTML= 'The distance bewtween (' + x1 + ',' + y1 + ') and ('+ x2 + ',' + y2 + ') is '+ distance;
}
<!doctype html>
<!-- distance.html Mason Boroff -->
<!-- =================================================== -->
<html>
<head>
<title> Distance Calculator </title>
</head>
<body>
<h2>Distance Calculator</h2>
<p>
Coordinate 1: (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br>
Coordinate 2: (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<br>
<input type="button" onclick="ShowDistance()" value="Calculate
Distance">
</p>
<hr>
<div id="outPut"> </div>
</body>
Run your code before posting a question.
function showDistance() {
var x1 = (parseInt(document.getElementById('xOne').value)).toFixed(4);
var x2 = (parseInt(document.getElementById('xTwo').value)).toFixed(4);
var y1 = (parseInt(document.getElementById('yOne').value)).toFixed(4);
var y2 = (parseInt(document.getElementById('yTwo').value)).toFixed(4);
var distance = Math.sqrt( Math.pow((x1-x2), 2) +
Math.pow((y1-y2), 2) );
document.getElementById('outPut')
.innerHTML= 'The distance bewtween (' +
x1 + ',' + y1 + ') and (' +
x2 + ',' + y2 + ') is '+ distance;
return distance;
}
<h2>Distance Calculator</h2>
<p>
Coordinate 1: (<input type="text" id="xOne" size=12 value=''> ,
<input type="text" id="yOne" size=12 value=''>)
<br>
Coordinate 2: (<input type="text" id="xTwo" size=12 value=''> ,
<input type="text" id="yTwo" size=12 value=''>)
<br>
<input type="button" onclick="showDistance()" value="Calculate
Distance";>
</p>
<hr>
<div id="outPut"> </div>
I want to initialize my var from HTML to my JavaScript file but my form is not working.if i initialize by myself the function is working but when initialize from HTML not working.
i test any thing comes to my mind but it is not working.
function DDA() {
var x1, x2, y1, y2 ,m;
x1=document.getElementById('x1').value;
x2=document.getElementById('x2').value;
y1=document.getElementById('y1').value;
y2=document.getElementById('y2').value;
if(x1==null||x1==""||x2==null||x2==""||y1==null||y1==""||y2==null||y2==""){
console.log('enter number');
return false;
}
m = (y2 - y1) / (x2 - x1);
console.log(`(${x1},${y1})`);
if (m > 1) {
for (var i = y1 + 1; i <= y2; i++) {
x1 = (x1 + (1 / m));
console.log(`(${Math.round(x1)},${i})`);
}
} else {
for (var i = x1 + 1; i <= x2; i++) {
y1 = (y1 + m);
console.log(`(${i},${Math.round(y1)})`);
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form name="myform" onsubmit=" return (DDA())" action="index.html" method="POST">
<input type="text" id="x1" placeholder="x1"><br>
<input type="text" id="x2" placeholder="x2"><br>
<input type="text" id="y1" placeholder="y1"><br>
<input type="text" id="y2" placeholder="y1"><br>
<input type="submit" id="submitform" >
</form>
<script src="tamrin.js">
</script>
</body>
</html>
I think your code run perfectly If you fill all the text box it prints in the console if any filed not filled it show the message as "enter the number" because of your validation.
simple numerical code to compute the hypotenuse with the numeric value, i dont know how to decpiher the hypotenuse code in Javascript language" hypo = the square_root of ( sidea squared plus sideb squared)", when i go to my webpage it just shows up blank...what am i missing please inform me on what it was thanks
<html>
<head>
<title> Quadratic</title>
<script type="text/javascript">
function Calculate() {
var a = document.getElementById("aBox").value;
var b = document.getElementById("bBox").value;
var c = document.getElementById("cBox").value;
var x = document.getElementById("xBox").value;
var y = 0;
document.getElementById('outputDiv').innerHTML= 'result y = : 'y = ax2 + bx + c;">
}
</head>
<body>
<h2>Quadratic</h2>
<p>
a: <input type="text" id="aBox" value="2">
<br>
b: <input type="text" id="bBox" value="3">
<br>
c: <input type="text" id="cBox" value="4">
<br>
x: <input type="text" id="xBox" value="5">
<br>
result y = : <input type="text" id="yBox" value="0">
</p>
<div id="outputDiv">
<input type="button" value="Calculate quadratic" onclick="Calculate();">
</div>
<hr>
</script>
</body>
</html>
You need to close the script tag in the right place
}
</script>
</head>
<body>
then your page will at least display
then you need to fix this
.innerHTML= 'result y = : 'y = ax2 + bx + c;">
Try this fiddle. http://jsfiddle.net/harendra/CpBZu/
This fixes your calculate function to calculate hypotenuse of square. You can do same for other squares as well.
function Calculate() {
var a = parseInt(document.getElementById("aBox").value);
var b = parseInt(document.getElementById("bBox").value);
var c = parseInt(document.getElementById("cBox").value);
var x = parseInt(document.getElementById("xBox").value);
var y = Math.sqrt(a*a+a*a);
document.getElementById('yBox').value=y
//document.getElementById('outputDiv').innerHTML= 'result y = : 'y = ax2 + bx + c";
}