Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Canvas Draw Arc

Posted in Canvas Tutorial
Updated on Oct 13, 2024
By Mari Selvan
👁️ 97 - Views
⏳ 4 mins
💬 1 Comment
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:

Syntax
Copied
Copy To Clipboard
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:

index.html
Copied
Copy To Clipboard
<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:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

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

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy