HTML5 canvas line width and color and how to set html5 canvas line width and color will be explained in this tutorial. HTML5 Canvas line has two important attribute width and color.In this tutorial we will explore how to set html5 canvas line width and color attributes.
HTML5 Canvas line color attribute takes values in three ways
1. value as a string
HTML5 Canvas color value can be given as string for example ‘red’ ,’blue’, ‘green’
code for setting color of html5 canvas line ,setting color value as string will be as follows:
2. html5 canvas line color value as hexadecimal
Value html5 Canvas line color can be set as hexadecimal value for example #ff0000 represent red .This value is set by seven character.
# represent color in hexa with six other characters.After
# first two digits indicates the value of red .This value can vary from
ff.In decimal system 00 is eqaul to 0 and ff equal to 255.
The next two digits ,middle digits, represent the value of color green.Green can also tool hexa value 00 to ff.
Last two digits represent the value of blue color.Blue color value can vary from 00 to ff.
In other words every color component can take one value from 256 available values.With these three componenents you can make million of combination of colors.Important color values in hexadecimal are given by.
Red ='#ff0000' Green ='#00ff00' Blue = '#0000ff' Yellow='#ffff00' Magenta ='#ff00ff' Cyan ='#00ff00' White ='#ffffff' Black ='#000000' Grey ='#888888'
3. html5 canvas line Color value as RGB
we can set value of three basic colors
by giving values from 0 to 255 to each color
the code for the RGB value of color will be
HTML5 Canvas line width
Canvas context has a property of
lineWidth which can be used to set the width of HTML5 Canvas line.The property of
lineWidth must be set before calling
we set the value of lineWidth attributes of html5 canvas line in pixel.
General code for the setting line width is
context.lineWidth = value in pixels
for example if we want to set line width 15 pixels we will write the code
HTML5 Canvas line width and Color exmple with complete code
<!DOCTYPE html > <html> <head> <title> setting Color and width of line of html5 canvas </title> </head> <body > <canvas id="myCanvas" width="600" height="400" style="border: 1px solid #0000ff;" > </canvas> <script> var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); context.beginPath(); context.moveTo(50, 50); context.lineTo(450, 350); // set line width context.lineWidth = 15; //set line color context.strokeStyle ='#ff0000'; context.stroke(); </script> </body> </html>
save the above file with name
and see the result in browsers.
HTML5canvas line width and color live demo on pencode