-
Charts JS uses HTML5 canvas elements to draw graphs onto a website.
-
the Chart JS script needs to be imported into the html page using
<script src = 'Chart.min.js'></script> -
a
<canvas>element needs to be created to draw the graph -
select the
<canvas>element by Id and use.getContext("2d"); -
creat the graph script:
new Chart(canvas_id).Line(lineData, lineOptions);new Chart(canvas_id).Pie(pieData, pieOptions);new Chart(canvas_id).Bar(barData);
The basic canvas element
<canvas id="tutorial" width="150" height="150"></canvas>- can be styled using border, margin, background, etc
- fallback content can be provided for older browsers that do not support canvas
- this content goes between the canvas tags
- scripts can test for browser support by using the getContext method
Drawing with Canvas:
- grid - one unit on the grid is one pixle, with (0,0) in the upper left corner
- all elements are placed relative to this origin
- width (x), height (y)
- canvas only supports rectangles and paths (all shapes other than rectangles must be made with paths)
- Rectangle Drawing:
fillRect(x, y, width, height)- solidstrokeRect(x, y, width, height)- outlineclearRect(x, y, width, height)- transparent
- Path Drawing:
beginPath()- creates new path- Path Methods
closePath()- straight line from current point to start to close path (optional)stroke()- draws shape outlinefill()- fills shapemoveTo(x, y)- moves path point without drawinglineTo(x, y)- draw a linearc(x, y, radius, startAngle, end Angle, counterclockwise)- draw an arcarcTo(x1, y1, x2, y2, radius)- draw arc attached to previous point
Path2D()creates a Path2D object- all path methods are available to this object
- Rectangle Drawing:
Color:
fillStyle = colorsets color when filling shapesstrokeStyle = colorsets color for outlines
Drawing Text:
fillText(text, x, y [,maxWidth])- fills in text at x,y positionstrokeText(text, x, y [, maxWidth])- outlines text at x,y position
Styling Text:
font = valuetextAlign = valuetextBaseline = valuedirection = value