Categories
Web development

HTML canvas strokeStyle Property

HTML canvas strokeStyle Property

The HTML canvas strokeStyle property defines the color, gradient, or pattern used for strokes.

value: color

Draw a square with a green stroke:

<!DOCTYPE html>
<html>
<body>

<canvas id="drawStroke" width="200" height="200" style="border:1px solid #333;"></canvas>

<script>
var c = document.getElementById("drawStroke");
var ctx = c.getContext("2d");
ctx.strokeStyle = "#2a9d8f";
ctx.strokeRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


value: gradient

Draw a square with a gradient stroke:

<!DOCTYPE html>
<html>
<body>

<canvas id="gradientStroke" width="200" height="200" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("gradientStroke");
var ctx = c.getContext("2d");

var gradient = ctx.createLinearGradient(0, 0, 150, 0);
gradient.addColorStop("0", "#e9c46a");
gradient.addColorStop("0.5", "#2a9d8f");
gradient.addColorStop("1.0", "#e76f51");

// Fill with gradient
ctx.strokeStyle = gradient;
ctx.lineWidth = 5;
ctx.strokeRect(50, 50, 100, 100);
</script>

</body>
</html>

Output:


Write the text with a gradient stroke:

<!DOCTYPE html>
<html>
<body>

<canvas id="gradienttextStroke" width="200" height="200" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("gradienttextStroke");
var ctx = c.getContext("2d");

ctx.font = "50px Arial";

// Create gradient
var gradient = ctx.createLinearGradient(0, 0, c.width, 0);
gradient.addColorStop("0", "#e76f51");
gradient.addColorStop("0.5", "#2a9d8f");
gradient.addColorStop("1.0", "#e9c46a");

// Fill with gradient
ctx.strokeStyle = gradient;
ctx.strokeText("Text", 50, 110);
</script>

</body>
</html>

Output:

Enjoy coding!