How to set the stoke style for Canvas

Description

We can use the stoke style with strokeStyle for Canvas.

Example


<!DOCTYPE HTML>
<html>
    <head>
        <script>
            window.onload = function(){<!--   w ww.  ja v  a  2  s.co  m-->
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                
        // set the line width to 10 pixels
                context.lineWidth = 10;
        // set the line color to blue
                context.strokeStyle = "blue";
        // position the drawing cursor
                context.moveTo(50, canvas.height - 50);
        // draw the line
                context.lineTo(canvas.width - 50, 50);
        // make the line visibile with the stroke color
                context.stroke();
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Click to view the demo

Example 2

When we set a style using the fillStyle or strokeStyle properties, we can specify a color using the CSS color values, using either a name or a color model.


<!DOCTYPE HTML>
<html>
<head>
<style>
canvas {<!--from w  ww. j a  v a  2  s.  c  o  m-->
      border: thin solid black;
      margin: 4px
}
</style>
</head>
<body>
      <canvas id="canvas" width="500" height="500"> 
      Your browser doesn't support the <code>canvas</code> element 
      </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            var offset = 10;
            var size = 50;
            var count = 3;
            ctx.lineWidth = 3;
            var fillColors = [ "black",  "red", "blue" ];
            var strokeColors = [ "rgb(20,20,20)", "rgb(255, 20, 20)", "rgb(0, 0, 255)" ];
            for ( var i = 0; i < count; i++) {
                  ctx.fillStyle = fillColors[i];
                  ctx.strokeStyle = strokeColors[i];
                  ctx.fillRect(i * (offset + size) + offset, offset, size, size);
                  ctx.strokeRect(i * (offset + size) + offset, (2 * offset) + size,size, size);
            }
      </script>
</body>
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window