Canvas
- Canvas Introduction
- Canvas Draw Rectangles
- Canvas Draw Lines
- Canvas Draw Bezier
- Canvas Draw Quadratic
- Canvas Draw Arc
- Canvas Draw Paths
- Canvas Manipulating Images
- Canvas Linear Gradients
- Canvas Radial Gradients
- Canvas Text
- Canvas Pattern
- Canvas Shadow
- Canvas States
- Canvas Translate
- Canvas Rotate
- Canvas Scale
- Canvas Transform
- Canvas Composition
Canvas Draw Arc
Photo Credit to CodeToFun
🙋 Introduction
When it comes to drawing graphics dynamically on web pages, the HTML5 <canvas> element provides a powerful toolset for developers. One of the fundamental shapes that can be drawn on the canvas is an arc, which is a portion of the circumference of a circle.
In this guide, we'll explore how to use the Canvas API to draw arcs programmatically.
💡 Syntax
To draw an arc on a canvas, you'll use the arc()
method of the CanvasRenderingContext2D interface. Here's the basic syntax:
context.arc(x, y, radius, startAngle, endAngle, anticlockwise);
🧰 Attributes
- x: The x-coordinate of the center of the arc.
- y: The y-coordinate of the center of the arc.
- radius: The radius of the arc.
- startAngle: The starting angle (in radians) where the arc begins.
- endAngle: The ending angle (in radians) where the arc ends.
- anticlockwise: Optional. Specifies whether the arc should be drawn in the anticlockwise direction (default is false).
📄 Example
Let's draw a simple arc on a canvas:
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
// Draw a red arc
context.beginPath();
context.arc(100, 100, 50, 0, Math.PI, false); // Draws a semicircle
context.strokeStyle = 'red';
context.lineWidth = 2;
context.stroke();
</script>
🧠 How it works?
In this example, we've drawn a semicircle centered at (100, 100) with a radius of 50 units. The arc starts from the rightmost point (0 radians) and ends at the leftmost point (Math.PI radians), forming a red semicircular arc.
🎉 Conclusion
Drawing arcs on a canvas opens up a world of possibilities for creating complex shapes and visual effects in web applications.
By mastering the arc()
method and understanding its parameters, you can dynamically generate arcs of varying sizes and styles to enhance the interactivity and aesthetics of your projects.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (Canvas Draw Arc), please comment here. I will help you immediately.