Graph of quadratic function with CanvasRenderingContext2D

Joined
May 9, 2024
Messages
1
Reaction score
0
Hello everyone,
I have a task in which I would like to implement the graphical visualisation of a quadratic equation in the interval x =[-10,10] and - if any exist - the corresponding zeros, using CanvasRenderingContext2D methods.
To convert the coordinates into pixel coordinates within the canvas: the coordinates into pixel coordinates within the canvas I would use following functions:
var toCanvasX = function ( x ) {
return (x + (max-min ) / 2 ) * canvas.width /( max - min );
}
var toCanvasY = function ( y ) {
return canvas.height - (y + (max-min ) / 2 ) * canvas.height / ( max - min);
}
The graph should look like this:

1715262449830.png

1715262449848.png

How can I solve it?
Code:
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<h1>Solver of Quadratic Equations</h1>
<script>
var a, b, c;
var output;

function check() {


a = document.forms["input_form"]["anumber"].value;
b = document.forms["input_form"]["bnumber"].value;
c = document.forms["input_form"]["cnumber"].value;


if (a == 0) {
output = "a cannot equal zero!";
} else if (isNaN(a)) {
output = "a has to be a number!";
} else if (isNaN(b)) {
output = "b has to be a number!";
} else if (isNaN(c)) {
output = "c has to be a number!";
} else {

var x1 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
var x2 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
output = "The polynomial <strong>" + (a == 1 ? "" : a) + "x\u00B2 + " + (b == 1 ? "" : b) + "x + " + c + " = 0</strong> has two zeros x1=" + x1 + "," + " " + "x2=" + x2;
}

document.getElementById("output").innerHTML = output;
}
</script>
</head>

<body>

This programme calculates zeros of quadratic polynomials of the form ax² + bx + c and graphically displays the solution in the interval x ∈ [-10,10].
<br><br>
<form name="input_form" action="javascript:check();">
a: <input type="text" name="anumber" required>
b: <input type="text" name="bnumber" required>
c: <input type="text" name="cnumber" required>
<br><br>
<input type="submit" value="Calculate zeros">
</form>

<p id="output"/>

</body>

</html>
 
Joined
Sep 21, 2022
Messages
171
Reaction score
24
I have no expertise of Javascript graphics, so I can't answer alexanderrm's question.

What I do find interesting is the way they convert real coordinates to pixel coordinates.

I'm going to suggest a general purpose function.
Code:
f(E,A,B,C,D)=(E-A)*(D-C)/(B-A)+C

----A-----B---- AB scale
----C-----D---- CD scale

f converts a number on the AB scale to the CD scale. A maps to C, and B maps to D. Direction doesn't matter, AB could be increasing while CD is decreasing.

pixelx=f(realx,-10,10,0,canvas.width)
pixely=f(realy,10,-10,0,canvas.height)

Going the other way is also simplified.

realx=f(pixelx,0,canvas.width,-10,10)
realy=f(pixely,0,canvas.height,10,-10)

It also converts between Celsius and Fahrenheit.

Off topic I know, but on the other hand, this isn't Stack Exchange.
 
Last edited:
Joined
Jul 4, 2023
Messages
475
Reaction score
58
You can achieve this easily by using simply trick for convert real coordinates to pixel coordinates.
JavaScript:
function toCanvasX(x) {
  return (x + 10) * canvas.width / 20;
}

function toCanvasY(y) {
  return canvas.height - (y + 10) * canvas.height / 20;
}

Check this
HTML:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Solver of Quadratic Equations</title>

    <style>
      .button {
        margin-top: 1rem;
      }
    </style>
  </head>

  <body>
    <h1>Solver of Quadratic Equations</h1>
    <canvas id="graph" width="600" height="400"></canvas>
    <p id="output"></p>

    <script>
      const canvas = document.querySelector('canvas#graph');
      const ctx = canvas.getContext('2d');
      let a, b, c;
      let output;

      function check(e) {
        e.preventDefault();

        a = parseFloat(document.querySelector('form #a-number').value);
        b = parseFloat(document.querySelector('form #b-number').value);
        c = parseFloat(document.querySelector('form #c-number').value);

        if (isNaN(a) || isNaN(b) || isNaN(c)) {
          output = 'All coefficients (a, b, c) must be valid numbers!';
        } else {
          const x1 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
          const x2 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a);
          output = 'The polynomial <strong>'
            + (a == 1 ? '' : a) + 'x² + '
            + (b == 1 ? '' : b) + 'x + '
            + c + ' = 0</strong> has two zeros x1=' + x1 + ', x2=' + x2;

          drawCoordinates();
          drawGraph();
          drawZeros(x1, x2);        
        }

        document.querySelector('#output').innerHTML = output;      
      }

      function drawCoordinates() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.lineWidth = 1;
        ctx.strokeStyle = 'black';

        ctx.beginPath();
        ctx.moveTo(0, canvas.height / 2);
        ctx.lineTo(canvas.width, canvas.height / 2);
        ctx.moveTo(canvas.width / 2, 0);
        ctx.lineTo(canvas.width / 2, canvas.height);      
        ctx.stroke();
        ctx.closePath();
      }

      function drawGraph() {
        ctx.strokeStyle = 'forestgreen';
        ctx.lineWidth = 2;

        ctx.beginPath();

        const STEP = 0.1;
        for (let x=-10; x<=10; x+=STEP) {
          const y = a * Math.pow(x, 2) + b * x + c;
          const canvasX = toCanvasX(x);
          const canvasY = toCanvasY(y);
          if (x == -10)
            ctx.moveTo(canvasX, canvasY);
          else
            ctx.lineTo(canvasX, canvasY);
        }

        ctx.stroke();
        ctx.closePath();
      }

      function drawZeros(x1, x2) {
        const zero1X = toCanvasX(x1);
        const zero1Y = toCanvasY(0);
        const zero2X = toCanvasX(x2);
        const zero2Y = toCanvasY(0);

        ctx.fillStyle = 'greenyellow';
        ctx.lineWidth = 2;
        ctx.strokeStyle = 'green';      

        ctx.beginPath();
        ctx.arc(zero1X, zero1Y, 5, 0, Math.PI * 2);
        ctx.fill();
        ctx.stroke();
        ctx.closePath();

        ctx.beginPath();
        ctx.arc(zero2X, zero2Y, 5, 0, Math.PI * 2);
        ctx.fill();
        ctx.stroke();
        ctx.closePath();      
      }

      function toCanvasX(x) {
        return (x + 10) * canvas.width / 20;
      }

      function toCanvasY(y) {
        return canvas.height - (y + 10) * canvas.height / 20;
      }
    </script>

    <p>
      This program calculates zeros of quadratic polynomials of the form ax² + bx + c and graphically displays the solution in the interval x ∈ [-10,10].
    </p>
    <form onsubmit="check(event)">
      a: <input type="number" id="a-number" name="a-number" value="0" required>
      b: <input type="number" id="b-number" name="b-number" value="0" required>
      c: <input type="number" id="c-number" name="c-number" value="0" required>

      <button type="submit" class="button">Calculate zeros</button>
    </form>
  </body>
</html>

1716631609078.png
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top