Clicking on HTML runs the code. The source code is
<!DOCTYPE html> <!-- Draw sin(x) from 0 to 2 PI. By Nasser M. Abbasi. March 6, 2020 --> <html> <head> </head> <body> <canvas id="canvas" width="300" height="200"></canvas> <div class="tab"> <button onclick="g_current_function=Math.sin; update()">sin</button> <button onclick="g_current_function=Math.cos; update()">cos</button> <button onclick="g_current_function=Math.tan; update()">tan</button> </div> <div> <label>x range (in units of PI)</label> <input type="range" id="to" value="2" min="1" max="10" step="1" oninput="document.getElementById('range').innerHTML=this.value; g_x_range=this.value; update()"/> <label id="range">2</label> </div> <SCRIPT> var canvas=document.getElementById('canvas'); var ctx=canvas.getContext('2d'); var g_current_function=Math.sin; var g_x_range=document.getElementById('range').innerHTML; //Move the origin from top-left ctx.translate(0, canvas.height/2); // and correct the y-scale ctx.scale(1, -1); function update() { //Scale the width so it is 2 PI and scale the hight so it // goes from -1..1 var horizontal_scale = g_x_range*Math.PI/canvas.width; var vertical_scale = canvas.height/2; //console.log("enter update"); //console.log("g_current_function=",g_current_function); //console.log("xrange=",xrange); //console.log("g_current_function(Math.PI/2)",g_current_function(Math.PI/2)); //These 4 lines is to clear canvas ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.restore(); //Draw the sine wave ctx.beginPath(); ctx.moveTo(0, 0); for (let x = 0; x <= canvas.width; x=x+canvas.width/60) { //console.log("x=",x,"y=",vertical_scale*g_current_function(x*horizontal_scale)); ctx.lineTo(x, vertical_scale*g_current_function(x*horizontal_scale) ); } ctx.strokeStyle = "black"; ctx.linewidth=2; ctx.stroke(); // draw x-axis ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(canvas.width, 0 ); ctx.linewidth=1; ctx.strokeStyle = "red"; ctx.stroke(); // draw y-axis ctx.beginPath(); ctx.moveTo(0, -canvas.height/2); ctx.lineTo(0,canvas.height/2); ctx.stroke(); } window.onload = function () { update() } </SCRIPT> </body> </html>