Jump to content

Getting JavaScript to work.


MacNala2

Recommended Posts

My problem is I am trying to improve the performance of a script which displays a graph  in an html camvas.

I want to embed the script in an external file and call it by an event in the html on the page that displays the graph.

The html file aggregate1.html woorks correctly and displays the graph ( chart1015.png ) on a canvas sized to suit the screen size you are using.

The script file (canvas.js) is my attempt to externalise the JavaScript.

Every time I try to call this script, as in example aggregate-new.html I get an error saying that script canvas is not defined.

How do I correct my error?

chart1015.png

aggregate1.html canvas.js aggregate1-new.html

Link to comment
Share on other sites

The canvas.js file that you attached is empty. It seems you've renamed the function canvas1() to myGraph() so you need to account for that when copying the Javascript function to another file.

Also make sure that your Javascript files are in the right location.

Your page has a redundant <script> tag.

As long as the files are in the right location, this works for me:

aggregate1-new.html

<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<img onload="myGraph()" hidden id="graph" src="chart1015.png" alt="The Graph" width="6" height="4">
<canvas id="canvas1">Your browser does not support the HTML canvas tag.</canvas>
<script src="../js/canvas.js"></script>
</body>
</html>

canvas.js

function myGraph() {
  let w = window.innerWidth;
  let h = window.innerHeight;
  let wc = w - 20;
  let hc = h - 25;
  let wi = 1389;
  let hi = 889;
  let hwr = w / h;
  if (hwr < 1.00 ) {
    window.alert("Height to Width ratio greater than or equal to 1.00 not recommended!");
  }
    document.getElementById("canvas1").width=wc;
    document.getElementById("canvas1").height=hc;
    var c = document.getElementById("canvas1");
    var ctx = c.getContext("2d");
    ctx.scale(wc / wi, hc / hi);
    var img = document.getElementById("graph");
    ctx.drawImage(img,15,0);
    document.getElementById("button").style.display='none';
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...