HTML Canvas – Adding Styles


HTML Canvas – Adding Styles



”;


Similar to colors we can also add various stlyes to difference shapes available in HTML5 Canvas. Let us see them one by one.

Styles to Lines

One way to draw a line in HTML5 is to use the lineTo path element. We can also beautify these lines using the various style properties.

Since most of the objects we create on canvas are drawn using lines we can stryle these objects using the line properties. The properties that are used for styling lines are listed in the below table.








S.No Property & Description Sample image
1

ineWidth

The width of the lines drawn can be assigned using this property. The thickness value of any line by default is 1 unit.

LineWidth
2

lineCap

This property is generally used to style the ends of the line. There are three accepted input values for the property which are ”butt”, ”round” and ”square”. The default value is always ”butt”.

LineCap
3

lineJoin

When two lines are about to be joined, this property can be used to set the appearance of the corners where lines are joined. The values accepted by the property are ”miter”, ”bevel”, and ”round”. The default value of the property is ”miter”. The property does not affect the lines as there is no joining area added.

LineJoin
4

miterLimit

The thickness of the junction is changed using the property when two angles join at a sharp angle. This property determines the distance of outside connection to which inside connection point can be placed. The default value is 10 but the possible values completely depend on the lines used.

MiterLimit
5

lineDashOffset

This specifies the dash pattern for the lines. This is used to make dotted and dash lined patterns. We can also use it in setLineDash() method and create animation effects.

LineDashOffset

Apart from these properties, two other methods can be used to apply styles for lines.

  • The getLineDash() method − This returns the current line-dash pattern containing an even number of positive numbers.

  • The setLineDash() method − To set the dash lines to create a shape or pattern using Canvas, this method is used. It takes segment array as inputs which consist of some line values. If nothing is given, a simple stroked line is given as output.

Example

Following code demonstrates lineWidth and lineCap properties. The implementation is given below.


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Styling lines</title>
      <style></style>
   </head>
   <body onload="linestyles();">
      <canvas id="canvas" width="300" height="200" style="border: 1px solid black;"></canvas>
      <script>
         function linestyles() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext(''2d'');
            // lineWidth property
            context.moveTo(30, 30);
            context.lineTo(30, 150);
            context.lineWidth = 5;
            context.stroke();
            // linecap round property
            context.beginPath();
            context.moveTo(80, 30);
            context.lineTo(80, 150);
            context.lineWidth = 10;
            context.lineCap = ''round'';
            context.stroke();
            context.closePath();
            // linecap butt property
            context.beginPath();
            context.moveTo(130, 30);
            context.lineTo(130, 150);
            context.lineWidth = 10;
            context.lineCap = ''butt'';
            context.stroke();
            context.closePath();
            // linecap square property
            context.beginPath();
            context.moveTo(180, 30);
            context.lineTo(180, 150);
            context.lineWidth = 10;
            context.lineCap = ''square'';
            context.stroke();
            context.closePath();
         }
      </script>
   </body>
</html>

Output

The output for the following code is given below.


Styles to Lines

Example

Following code demonstrates the lineJoin and miterlimit properties. The miterlimit property is demonstrated with values ”2 units” and ”20 units” respectively. The code is given below.


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Styling lines</title>
      <style></style>
   </head>
   <body onload="linestyles();">
      <canvas id="canvas" width="600" height="400" style="border: 1px solid black;"></canvas>
      <script>
         function linestyles() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext(''2d'');
            // linejoin round property
            context.moveTo(30, 30);
            context.lineTo(30, 150);
            context.lineTo(150, 150);
            context.lineTo(150, 30);
            context.lineJoin = ''round'';
            context.lineWidth = 10;
            context.stroke();
            // linejoin bevel property
            context.beginPath();
            context.moveTo(200, 30);
            context.lineTo(200, 150);
            context.lineTo(320, 150);
            context.lineTo(320, 30);
            context.lineJoin = ''bevel'';
            context.lineWidth = 10;
            context.stroke();
            context.closePath();
            // linejoin miter property
            context.beginPath();
            context.moveTo(370, 30);
            context.lineTo(370, 150);
            context.lineTo(490, 150);
            context.lineTo(490, 30);
            context.lineJoin = ''miter'';
            context.lineWidth = 10;
            context.stroke();
            context.closePath();
            // miterlimit property with value 2
            context.beginPath();
            context.moveTo(50, 200);
            context.lineTo(120, 350);
            context.lineTo(190, 200);
            context.miterLimit = 2;
            context.lineJoin = ''miter'';
            context.lineWidth = 25;
            context.stroke();
            context.closePath();
            // miterlimit property with value 20
            context.beginPath();
            context.moveTo(250, 200);
            context.lineTo(320, 350);
            context.lineTo(390, 200);
            context.miterLimit = 20;
            context.lineJoin = ''miter'';
            context.lineWidth = 25;
            context.stroke();
            context.closePath();
         }
      </script>
   </body>
</html>

Output

Following code gives the output as


Styles to Lines Example

Example

The following example uses setLineDash method and lineDashOffset property value to specify dish patterns for drawing shapes using lines. The implementation code is given below.


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Styling lines</title>
      <style></style>
   </head>
   <body onload="linestyles();">
      <canvas id="canvas" width="350" height="200" style="border: 1px solid black;"></canvas>
      <script>
         function linestyles() {
            var canvas = document.getElementById("canvas");
            var ctx = canvas.getContext(''2d'');
            var offset = 0;

            function draw() {
               ctx.clearRect(0, 0, canvas.width, canvas.height);
               ctx.setLineDash([50, 10]);
               ctx.lineDashOffset = offset;
               ctx.strokeRect(10, 10, 250, 125);
            }

            function animate() {
               offset++;
               if (offset > 25) {
                  offset = 0;
               }
               draw();
               setTimeout(animate, 50);
            }
            animate();
         }
      </script>
   </body>
</html>

Output

The code returns the output as shown below. Paste the code in the editor to see the animation effect.


SetLineDash

Gradients

We can simply fill and stroke shapes using gradients just like drawing a shape on a Canvas element. There are three types of gradients available in Canvas, they are linear, radial, and conic. We can create gradient objects using three methods. Each method is listed in the below table.






S.No Method & Description
1

createLinearGradient(x1, y1, x2, y2)

Creates a linear gradient object having starting point as (x1,y1) and an end point as (x2,y2).

2

createRadialGradient(x1, y1, r1, x2, y2, r2)

This method is used for creating a radial gradient object. It takes two circles as its parameters where the first circle radius is r1 and the center co-ordinates are (x1,y1). The second circle radius is r2 and its center co-ordinates are (x2,y2).

3

createConicGradient(angle, x, y)

To create a conic gradient object, this method is used which takes the starting angle in radians and the position point (x, y) as its parameters.

After creating a canvas gradient object, we can color it using the addColorStop() method. Its syntax and parameters are given below.

Canvas.addColorStop(position, color) − It creates a color stop for the canvas object created. The parameter position takes values between 0 and 1 which defines the position of color in the gradient. The color parameter is the color input that is rendered to the gradient object. There is no limit on the number of color stops for the single gradient object.

Example 1 (linear gradient)

Following example shows how linear gradient is implemented. The code is given below.


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Gradients</title>
      <style></style>
   </head>
   <body onload="gradients();">
      <canvas id="canvas" width="500" height="300" style="border: 1px solid black;"></canvas>
      <script>
         function gradients() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext(''2d'');
            // linear gradient
            var lineargrad = context.createLinearGradient(0, 0, 200, 100);
            context.fillStyle = lineargrad;
            lineargrad.addColorStop(0, ''orange'');
            lineargrad.addColorStop(0.5, ''white'');
            lineargrad.addColorStop(1, ''green'');
            context.fillRect(10, 10, 190, 80);
         }
      </script>
   </body>
</html>

Output

The linear gradient object formed from the above code is


Gradients

Example 2 (radial-gradient)

Following code demonstrates how a radial gradient is implemented in the Canvas element. We take two circles have same centers but different radius and colors to show the gradients.


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Gradients</title>
      <style></style>
   </head>
   <body onload="gradients();">
      <canvas id="canvas" width="400" height="400" style="border: 1px solid black;"></canvas>
      <script>
         function gradients() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext(''2d'');
            var radialgrad = context.createRadialGradient(150, 150, 25, 150, 150, 100);
            radialgrad.addColorStop(0, ''orange'');
            radialgrad.addColorStop(1, ''blue'');
            context.fillStyle = radialgrad;
            context.fillRect(10, 10, 300, 300);
         }
      </script>
   </body>
</html>

Output

The output generated by the above code is


Example Radial-Gradient

Example 3 (conic gradient)

The following example shows how conic gradient can build a gradient object that looks like a 3D element. It is actually a 2D shape. The implementation is given below.


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Gradients</title>
      <style></style>
   </head>
   <body onload="gradients();">
      <canvas id="canvas" width="400" height="400" style="border: 1px solid black;"></canvas>
      <script>
         function gradients() {
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext(''2d'');
            var conicgradient = context.createConicGradient(2, 62, 75);
            conicgradient.addColorStop(0, ''white'');
            conicgradient.addColorStop(0.75, ''black'');
            context.fillStyle = conicgradient;
            context.fillRect(12, 25, 200, 150);
         }
      </script>
   </body>
</html>

Output

The gradient object formed for the above code is


Example Conic Gradient

Patterns

Paintings are drawn on Canvas. Hence the name Canvas element is coined in HTML5. The Canvas element can be used to draw and design various patterns using pattern methods which are very attractive and has huge applications. It is commonly used in interior house designing. Image patterns can be drawn by this property on the Canvas element. The method used to create a pattern is given below

createPattern(image, type)

This method creates a Canvas pattern object which generates the image many times in the given space inside the Canvas. The parameter ”image” takes an image, and video as an input and makes it a pattern. There are four possible string inputs for the ”type” parameter and are listed below

  • repeat − this prints the input image in both horizontal and vertical positions.

  • repeat-x − the image is only repeated horizontally across the Canvas element.

  • repeat-y − the image is repeated vertically but not horizontally.

  • no-repeat − the image is not repeated and is used only once.

This method only works when the image is loaded before it is called. If the image is not loaded, the pattern is drawn incorrectly which may lead to some errors resulting in not displaying the pattern.

Example

Let us create a pattern using the method. Following shows the implementation


<html lang="en">
   <head>
      <title>Pattern</title>
      <style>
         #canvas {
            background-color: black;
         }
      </style>
   </head>
   <body onload="pattern();">
      <canvas id="canvas" width="555" height="555" style="border: 1px solid black;"></canvas>
      <script>
         function pattern() {
            var canvas = document.getElementById(''canvas'');
            var context = canvas.getContext(''2d'')
            var image = new Image();
            image.src = ''https://www.tutorialspoint.com/themes/home/tp-diamond-logo-white.png'';
            image.onload = function() {
               // change type parameter in the method to see how the pattern is displayed.
               var pattern = context.createPattern(image, ''repeat'');
               context.fillStyle = pattern;
               context.fillRect(0, 0, canvas.width, canvas.height);
            }
         }
      </script>
   </body>
</html>

Output

The pattern generated by the above code is given below


Patterns

Shadows

Shadows make the shapes drawn inside the Canvas element more animative. Four properties can be applied to the Canvas element to use shadows. They are listed below

  • shadowOffsetX − The property takes the float value and indicates the horizontal distance of the shadow from the shape. The default value is 0 and the property value does not get affected by the transformation matrix. Using negative values makes the shadow move to the left of the shape.

  • shadowOffsetY − This property indicates at how much distance the shadow must be extended vertically. It takes float values, and the default value is 0. Using negative values makes the shadow move to the top. Like the above property, it is not affected by the transformation matrix.

  • shadowBlur − It indicates how blurred the shadow should be. It takes the float value as the input. The default value is 0 and it does not indicate the pixel numbers.

  • shadowColor − It takes standard CSS color as the input and applies it for the shadow effect. It is transparent black by default.

Example

The following example demonstrate shadow offset X and Y properties of shadow in three different shapes. The first square shows how shadowOffsetX is used, second square shows how shadowOffsetY is implemented, and the third square uses both the properties. The code is given below.


<!DOCTYPE html>
<html lang="en">
   <head>
      <title>shadow</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body onload="shadow();">
      <canvas id="canvas" width="555" height="200" style="border: 1px solid black;"></canvas>
      <script>
         function shadow() {
            var canvas = document.getElementById(''canvas'');
            var context = canvas.getContext(''2d'');
            // using shadow offset x
            context.beginPath();
            context.shadowOffsetX = 20;
            context.shadowColor = ''grey'';
            context.rect(50, 50, 75, 75);
            context.fillStyle = ''blue'';
            context.fill();
            context.closePath();
            // using shadow offset y
            context.beginPath();
            context.shadowOffsetX = 0;
            context.shadowOffsetY = 20;
            context.shadowColor = ''grey'';
            context.rect(200, 50, 75, 75);
            context.fillStyle = ''green'';
            context.fill();
            context.closePath();
            // using shadow offset x and y
            context.beginPath();
            context.shadowOffsetX = 30;
            context.shadowOffsetY = 30;
            context.shadowColor = ''grey'';
            context.rect(350, 50, 75, 75);
            context.fillStyle = ''violet'';
            context.fill();
            context.closePath();
         }
      </script>
   </body>
</html>

Output

The shadows formed for the above code is


Shadows

Example

Following code implements the shadowBlur and shadowColor properties to the Canvas element.


<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>shadow</title>
      <style>
         body {
            margin: 10px;
            padding: 10px;
         }
      </style>
   </head>
   <body onload="shadow();">
      <canvas id="canvas" width="200" height="200" style="border: 1px solid black;"></canvas>
      <script>
         function shadow() {
            var canvas = document.getElementById(''canvas'');
            var context = canvas.getContext(''2d'');
            context.shadowOffsetX = 20;
            context.shadowOffsetY = 20;
            context.shadowBlur = 10;
            context.shadowColor = ''red'';
            context.arc(90, 90, 50, 1 * Math.PI, 5 * Math.PI);
            context.fillStyle = ''black'';
            context.fill();
         }
      </script>
   </body>
</html>

Output

The output for the above code is


Example Shadows

Advertisements

”;

Leave a Reply

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