How to Draw Curves With Javascript
The introduction of HTML5 brought with it support for the "canvas" element, which allows developers to create dynamic 2D shapes and bitmap images in standard HTML pages by using JavaScript. In particular, this new element supports curves in the form of circle arcs. To create such a shape, you must first define a canvas element, pull its properties into JavaScript and then set up those properties of the arc necessary for the curve to display the way you would like it to.
Instructions
-
-
1
Create a canvas between the page's "body" tags and assign it an ID:
<canvas id="canvas-example"></canvas>
-
2
Create a JavaScript function between the "head" tags of your page that loads upon startup:
<script type="text/javascript">
window.onload = function()
{
};
</script> -
-
3
Initialize the canvas using the "getElementById" and "getContext" methods, as well as two variables:
var my_canvas = document.getElementById("canvas-example");
var my_canvas_content = my_canvas.getContext("2d"); -
4
Declare five variables and assign them values based on the center x and y coordinates of the circle, the circle's radius, the curve's starting angle and the curve's ending angle:
var starting_x_coordinate = 200;
var starting_y_coordinate = 160;
var curve_radius = 70;
var curve_starting_angle = 1.0 * Math.PI;
var curve_ending_angle = 1.9 * Math.PI; -
5
Create the curve path by inserting the declared variables into the "arc" method:
my_canvas_content.arc(starting_x_coordinate, starting_y_coordinate, curve_radius, curve_starting_angle, curve_ending_angle);
-
6
Assign the curve a width and color using the "lineWidth" and "strokeStyle" properties:
my_canvas_content.lineWidth = 15;
my_canvas_content.strokeStyle = "black" -
7
Draw the curve by using the "stroke" method:
my_canvas_content.stroke();
-
1
References
- Photo Credit Hemera Technologies/PhotoObjects.net/Getty Images