I decided to day to embark on element and I can say so far it have been nightmare to get it work. All I want is to plot a sine graph. So after good reading I still cannot either get origins nor get it plot. Below is what I have tried (my first time ever with that tag so excuse my ignorance). What makes me wonder is the guy here have it but the codes are hard to understand for beginner like me.
HTML
<!DOCTYPE html> <html> <head> <title>Graphing</title> <link type="text/css" rel="Stylesheet" href="graph.css" /> <script type="text/JavaScript" src="graph.js" ></script> </head> <body> <canvas id="surface">Canvas not Supported</canvas> </body> </html>
CSS
#surface { width:300; height:225; border: dotted #FF0000 1px; }
JavScript
window.onload = function() { var canvas = document.getElementById("surface"); var context = canvas.getContext("2d"); arr = [0,15, 30,45,60, 90,105, 120, 135, 150, 165, 180 ]; var x=0; var y = 0; for(i=0; i<arr.length; i++) { angle = arr[i]*(Math.PI/180); //radians sine = Math.sin(angle); context.moveTo(x,y); context.lineTo(angle,sine); context.stroke(); //set current varibles for next move x = angle; y = sine; } }
Advertisement
Answer
Since the range of sin x
is [-1,1]
, it will only return numbers between -1 and 1, and that means all you will be drawing is a dot on the screen.
Also I see that you have an array ranging from 0 to 180. I believe you are trying to draw the curve with x
from 0 degree to 180 degree? You don’t really need to do this (anyway 12 points are not enough to draw a smooth line). Just do it with a for
loop, with lines
being the number of fragments.
First we start off by moving the point to the left of the canvas:
context.moveTo(0, 100 /*somewhere in the middle*/); //initial point
In most cases the first point won’t be in the middle. But for sine it is. (You might want to fix it later though.)
for (var i = 0; i < lines; i++) { //draw line }
That’s the loop drawing the curve. But what should we put inside? Well you can just take the number returned by the sine function and scale it up, flip it upside down, and shift it down half the way. I do that because the coordinate system in JavaScript is 0,0 in the top left instead of in the bottom left.
var sine = Math.sin(i/scale*2)*scale; context.lineTo(i*frag, -sine+scale); //i * frag = the position of x scaled up //-sine + scale = the position of y, flipped, scaled, shifted down //i/scale*2 = random scale I put in... you might want to figure out the // correct scale with some math
So that’s it. Viola, you have successfully plotted a graph in JavaScript.
Oh yes, don’t forget to actually tell it to draw it on the canvas after the for
loop has done its job:
context.stroke();
The demo: http://jsfiddle.net/DerekL/hK5rC/
PS: I see that you are trying to resize the canvas using CSS. Trust me, it won’t work. 🙂 You will have to define the dimension in HTML.