How to add dashed stroke to a Triangle using FabricJS?

In this tutorial, we are going to learn how to add a dashed stroke to a Triangle using FabricJS. Triangle is one of the various shapes provided by FabricJS. In order to create a Triangle, we will have to create an instance of fabric.Triangle class and add it to the canvas. The strokeDashArray property allows us to specify a dash pattern for the object's stroke.

Syntax

new fabric.Triangle( { strokeDashArray: Array }: Object)

Parameters

  • options (optional) ? This parameter is an Object which provides additional customizations to our triangle. Using this parameter, properties such as colour, cursor, stroke width, and a lot of other properties can be changed related to the object of which strokeDashArray is a property.

Options Keys

  • strokeDashArray ? This property accepts an Array which allows us to specify a dash pattern for the object's stroke. For example, if we pass an array with values [2,3], it means a dash pattern of 2px dash and 3px gap and repeating this pattern infinitely.

Example 1

Default appearance of an object's stroke

Let's see a code example that depicts the default appearance of the stroke of a triangle object. Since we have not used the strokeDashArray property, there is no dash pattern being displayed.



   
   


   

Default appearance of an object's stroke

   

You can see there is no dash pattern in the stroke

       

Example 2

Passing strokeDashArray property as key

In this example, we are passing the strokeDashArray property a value of [9,2]. This means that a dash pattern will be created such that there is a 9px long line, followed by a 2px gap, then again a 9px long line will be drawn and so on.



   
   


   

Passing strokeDashArray property as key

   

You can see there is a dash pattern in the stroke now

       
Updated on: 2022-06-24T11:55:22+05:30

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements