Canvas Path tutorials-1

Canvas Path tutorials-1
Nikhil
Published on 2021-07-05 08:13:24

arc (a path command)


context.arc(centerX, centerY, radius, startingRadianAngle, endingRadianAngle)

Draws a circular arc given a centerpoint, radius and starting & ending angles. The angles are expressed as radians.

To convert degrees to radians you can use this formula: radians = degrees * Math.PI / 180;. Angle 0 faces directly rightward from the center of the arc.

By default, the arc is drawn clockwise, An optional [true|false] parameter instructs the arc to be drawn counterclockwise: context.arc(10,10,20,0,Math.PI*2,true)

<!doctype html>
<html>
<head>
    <style>
        body {
            background-color: white;
        }

        #canvas {
            border: 1px solid red;
        }
    </style>
    <script>
        window.onload = (function() {
            // get a reference to the canvas element and its context
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            // arguments
            var centerX = 50;
            var centerY = 50;
            var radius = 30;
            var startingRadianAngle = Math.PI * 2 * ; // start at 90 degrees == centerY+radius
            var endingRadianAngle = Math.PI * 2 * .75; // end at 270 degrees (==PI*2*.75 in radians)
            // A partial circle (i.e. arc) drawn using the "arc" command
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, startingRadianAngle, endingRadianAngle);
            ctx.stroke();
        }); // end window.onload
    </script>
</head>
<body>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

 

To draw a complete circle you can make endingAngle = startingAngle + 360 degrees (360 degrees == Math.PI2).

<!doctype html>
<html>
<head>
    <style>
        body {
            background-color: white;
        }

        #canvas {
            border: 1px solid red;
        }
    </style>
    <script>
        window.onload = (function() {
            // get a reference to the canvas element and its context
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            // arguments
            var centerX = 50;
            var centerY = 50;
            var radius = 30;
            var startingRadianAngle = 0; // start at 0 degrees
            var endingRadianAngle = Math.PI * 2; // end at 360 degrees (==PI*2 in radians)
            // A complete circle drawn using the "arc" command
            ctx.beginPath();
            ctx.arc(centerX, centerY, radius, startingRadianAngle, endingRadianAngle);
            ctx.stroke();
        }); // end window.onload
    </script>
</head>
<body>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

 

quadraticCurveTo (a path command)


context.quadraticCurveTo(controlX, controlY, endingX, endingY)

Draws a quadratic curve starting at the current pen location to a given ending coordinate. Another given control coordinate determines the shape (curviness) of the curve.

<!doctype html>
<html>
<head>
    <style>
        body {
            background-color: white;
        }

        #canvas {
            border: 1px solid red;
        }
    </style>
    <script>
        window.onload = (function() {
            // get a reference to the canvas element and it's context
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            // arguments
            var startX = 25;
            var startY = 70;
            var controlX = 75;
            var controlY = 25;
            var endX = 125;
            var endY = 70;
            // A quadratic curve drawn using "moveTo" and "quadraticCurveTo" commands
            ctx.beginPath();
            ctx.moveTo(startX, startY);
            ctx.quadraticCurveTo(controlX, controlY, endX, endY);
            ctx.stroke();
        }); // end window.onload
    </script>
</head>
<body>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

 

bezierCurveTo (a path command)


context.bezierCurveTo(control1X, control1Y, control2X, control2Y, endingX, endingY)

Draws a cubic Bezier curve starting at the current pen location to a given ending coordinate. Another 2 given control coordinates determine the shape (curviness) of the curve.

<!doctype html>
<html>
<head>
    <style>
        body {
            background-color: white;
        }

        #canvas {
            border: 1px solid red;
        }
    </style>
    <script>
        window.onload = (function() {
            // get a reference to the canvas element and it's context
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            // arguments
            var startX = 25;
            var startY = 50;
            var controlX1 = 75;
            var controlY1 = 10;
            var controlX2 = 75;
            var controlY2 = 90;
            var endX = 125;
            var endY = 50;
            // A cubic bezier curve drawn using "moveTo" and "bezierCurveTo" commands
            ctx.beginPath();
            ctx.moveTo(startX, startY);
            ctx.bezierCurveTo(controlX1, controlY1, controlX2, controlY2, endX, endY);
            ctx.stroke();
        }); // end window.onload
    </script>
</head>
<body>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

 

arcTo (a path command)


context.arcTo(pointX1, pointY1, pointX2, pointY2, radius);

Draws a circular arc with a given radius. The arc is drawn clockwise inside the wedge formed by the current pen location and given two points: Point1 & Point2.A line connecting the current pen location and the start of the arc is automatically drawn preceding the arc.

<!doctype html>
<html>
<head>
    <style>
        body {
            background-color: white;
        }

        #canvas {
            border: 1px solid red;
        }
    </style>
    <script>
        window.onload = (function() {
            // get a reference to the canvas element and it's context
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            // arguments
            var pointX0 = 25;
            var pointY0 = 80;
            var pointX1 = 75;
            var pointY1 = 0;
            var pointX2 = 125;
            var pointY2 = 80;
            var radius = 25;
            // A circular arc drawn using the "arcTo" command. The line is automatically drawn.
            ctx.beginPath();
            ctx.moveTo(pointX0, pointY0);
            ctx.arcTo(pointX1, pointY1, pointX2, pointY2, radius);
            ctx.stroke();
        }); // end window.onload
    </script>
</head>
<body>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

 

rect (a path command)


context.rect(leftX, topY, width, height)

Draws a rectangle given a top-left corner and a width & height.

<!doctype html>
<html>
<head>
    <style>
        body {
            background-color: white;
        }

        #canvas {
            border: 1px solid red;
        }
    </style>
    <script>
        window.onload = (function() {
            // get a reference to the canvas element and it's context
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            // arguments
            var leftX = 25;
            var topY = 25;
            var width = 40;
            var height = 25;
            // A rectangle drawn using the "rect" command.
            ctx.beginPath();
            ctx.rect(leftX, topY, width, height);
            ctx.stroke();
        }); // end window.onload
    </script>
</head>
<body>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

 

The context.rect is a unique drawing command because it adds disconnected rectangles.

These disconnected rectangles are not automatically connected by lines.

<!doctype html>
<html>
<head>
    <style>
        body {
            background-color: white;
        }

        #canvas {
            border: 1px solid red;
        }
    </style>
    <script>
        window.onload = (function() {
            // get a reference to the canvas element and it's context
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext("2d");
            // arguments
            var leftX = 25;
            var topY = 25;
            var width = 40;
            var height = 25;
            // Multiple rectangles drawn using the "rect" command.
            ctx.beginPath();
            ctx.rect(leftX, topY, width, height);
            ctx.rect(leftX + 50, topY + 20, width, height);
            ctx.rect(leftX + 100, topY + 40, width, height);
            ctx.stroke();
        }); // end window.onload
    </script>
</head>
<body>
    <canvas id="canvas" width=200 height=150></canvas>
</body>
</html>

 

closePath (a path command)


context.closePath()

Draws a line from the current pen location back to the beginning path coordinate. For example, if you draw 2 lines forming 2 legs of a triangle, closePath will "close" the triangle by drawing the third leg of the triangle from the 2nd leg's endpoint back to the first leg's starting point.

A Misconception explained!

This command's name often causes it to be misunderstood. context.closePath is NOT an ending delimiter to context.beginPath. Again, the closePath command draws a line -- it does not "close" a beginPath.

This example draws 2 legs of a triangle and uses closePath to complete (close?!) the triangle by drawing the third leg. What closePath is actually doing is drawing a line from the second leg's endpoint back to the first leg's starting point.

<script>
    window.onload = (function() {
        // get a reference to the canvas element and it's context
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        // arguments
        var topVertexX = 50;
        var topVertexY = 50;
        var rightVertexX = 75;
        var rightVertexY = 75;
        var leftVertexX = 25;
        var leftVertexY = 75;
        // A set of line segments drawn to form a triangle using
        // "moveTo" and multiple "lineTo" commands
        ctx.beginPath();
        ctx.moveTo(topVertexX, topVertexY);
        ctx.lineTo(rightVertexX, rightVertexY);
        ctx.lineTo(leftVertexX, leftVertexY);
        // closePath draws the 3rd leg of the triangle
        ctx.closePath()
        ctx.stroke();
    }); // end window.onload
</script>

 

beginPath (a path command)


context.beginPath()

Begins assembling a new set of path commands and also discards any previously assembled path. It also moves the drawing "pen" to the top-left origin of the canvas (==coordinate[0,0]).

Although optional, you should ALWAYS start a path with beginPath

The discarding is an important and often overlooked point. If you don't begin a new path with beginPath, any previously issued path commands will automatically be redrawn.

These 2 demos both attempt to draw an "X" with one red stroke and one blue stroke. This first demo correctly uses beginPath to start it's second red stroke. The result is that the "X" correctly has both a red and a blue stroke.

<script>
    window.onload = (function() {
        // get a reference to the canvas element and it's context
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        // draw a blue line
        ctx.beginPath();
        ctx.moveTo(30, 30);
        ctx.lineTo(100, 100);
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 3;
        ctx.stroke();
        // draw a red line
        ctx.beginPath(); // Important to begin a new path!
        ctx.moveTo(100, 30);
        ctx.lineTo(30, 100);
        ctx.strokeStyle = 'red';
        ctx.lineWidth = 3;
        ctx.stroke();
    }); // end window.onload
</script>

This second demo incorrectly leaves out beginPath on the second stroke. The result is that the "X" incorrectly has both red strokes.

The second stroke() is draws the second red stroke.

But without a second beginPath, that same second stroke() also incorrectly redraws the first stroke. Since the second stroke() is now styled as red, the first blue stroke is overwritten by an incorrectly colored red stroke.

<script>
    window.onload = (function() {
        // get a reference to the canvas element and it's context
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        // draw a blue line
        ctx.beginPath();
        ctx.moveTo(30, 30);
        ctx.lineTo(100, 100);
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 3;
        ctx.stroke();
        // draw a red line
        // Note: The necessary 'beginPath' is missing!
        ctx.moveTo(100, 30);
        ctx.lineTo(30, 100);
        ctx.strokeStyle = 'red';
        ctx.lineWidth = 3;
        ctx.stroke();
    }); // end window.onload
</script>

 

lineCap (a path styling attribute)


context.lineCap=capStyle // butt (default), round, square

Sets the cap style of line starting points and ending points.

  • butt, the default lineCap style, shows squared caps that do not extend beyond the line's starting and ending points.
  • round, shows rounded caps that extend beyond the line's starting and ending points.
  • square, shows squared caps that extend beyond the line's starting and ending points.

 

lineJoin (a path styling attribute)


context.lineJoin=joinStyle // miter (default), round, bevel

Sets the style used to connect adjoining line segments.

  • miter, the default, joins line segments with a sharp joint.
  • round, joins line segments with a rounded joint.
  • bevel, joins line segments with a blunted joint.

 

strokeStyle (a path styling attribute)


context.strokeStyle=color
Sets the color that will be used to stroke the outline of the current path.
These are color options (these must be quoted):

  • A CSS named color, for example context.strokeStyle='red'
  • A hex color, for example context.strokeStyle='#FF0000'
  • An RGB color, for example context.strokeStyle='rgb(red,green,blue)' where red, green & blue are integers 0-255 indicating the strength of each component color.
  • An HSL color, for example context.strokeStyle='hsl(hue,saturation,lightness)' where hue is an integer 0-360 on the color wheel and saturation & lightness are percentages (0-100%) indicating the strength of each component.
  • An HSLA color, for example context.strokeStyle='hsl(hue,saturation,lightness,alpha)' where hue is an integer 0-360 on the color wheel and saturation & lightness are percentages (0-100%) indicating the strength of each component and alpha is a decimal value 0.00-1.00 indicating the opacity.

You can also specify these color options (these options are objects created by the context):

  • A linear gradient which is a linear gradient object created with context.createLinearGradient
  • A radial gradient which is a radial gradient object created with context.createRadialGradient
  • A pattern which is a pattern object created with context.createPattern

ATutorialHub Related Guide

Comments (8)

Leave a Comment

Your email address will not be published. Required fields are marked*

User Comments

html tutorial comments

panduranga gupta

2021-07-05 07:03:13

good website for learning and help me a lot

html tutorial comments

raju

2021-09-25 14:58:47

The awsome website i am looking like for a long time, good work atutorialhub team keep doing

html tutorial comments

Shivani

2021-09-01 15:03:56

Learning a lot from the courses present on atutorialhub. The courses are very well explained. Great experience

html tutorial comments

Harshitha

2021-09-10 15:05:45

It is very helpful to students and easy to learn the concepts

html tutorial comments

Sowmya

2021-09-14 15:06:41

Great job Tutorials are easy to understand Please make use of it

html tutorial comments

Zain Khan

2021-09-18 15:07:23

Great content and customized courses.

html tutorial comments

Rudrakshi Bhatt

2021-09-09 15:08:10

Well structured coursed and explained really well!

html tutorial comments

Pavana Somashekar

2021-09-11 15:09:08

Good platform for beginners and learn a lot on this website