The stroke()
method does the drawing
for the path defined.
The default color is black.
We can use the strokeStyle
property to change
the stroke style to color or gradient.
![]() |
![]() |
![]() |
![]() |
![]() |
|
---|---|---|---|---|---|
stroke() |
Yes | Yes | Yes | Yes | Yes |
context.stroke();
The following code uses stroke to draw a line.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
var ctx = document.getElementById("canvas").getContext("2d");
<!--from w w w .j a v a2 s. c om-->
ctx.moveTo(0,0);
ctx.lineTo(480,0);
ctx.stroke();
</script>
</body>
</html>
The code above is rendered as follows:
The following code sets the stroke style before calling
the stroke()
method.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
var ctx = document.getElementById("canvas").getContext("2d");
<!--from ww w. j a v a 2s . c om-->
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 400);
ctx.lineTo(300, 100);
ctx.strokeStyle = "red";
ctx.stroke();
</script>
</body>
</html>
The code above is rendered as follows:
The following code draws rectangles with various colors.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width='500px' height='200px'/>
<script type='text/javascript'>
var stage= document.getElementById('canvas');
var context = stage.getContext('2d');
<!--from ww w. j a va2s . c o m-->
context.beginPath();
context.rect(88, 10, 200, 100);
context.fillStyle = "#8ED6FF";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
context.rotate(0.5);
context.beginPath();
context.rect(138, 50, 200, 100);
context.fillStyle = "#FE8E9D";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
context.rotate(-0.5);
context.beginPath();
context.rect(188, 90, 200, 100);
context.fillStyle = "#FEEF8E";
context.fill();
context.lineWidth = 5;
context.strokeStyle = "black";
context.stroke();
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to draw an arrow.
<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" style='background-color:#EEE;' width='500px' height='200px'/>
<script type='text/javascript'>
var canvas= document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();<!--from w ww . j a v a 2 s .com-->
ctx.moveTo(50,50);
ctx.lineTo(150,50);
ctx.lineTo(100,25);
ctx.moveTo(150,50);
ctx.lineTo(100,75);
ctx.stroke();
</script>
</body>
</html>
The code above is rendered as follows: