Transparency

In this chapter you will learn:

  1. How to set color to transparency when drawing on canvas

Using Transparency

We can specify a fillStyle or strokeStyle value using the rgba function instead of rgb. We can also use the globalAlpha drawing state property.

<!DOCTYPE HTML><!-- java2s . c  o m-->
<html>
<head>
<style>
canvas {
      border: thin solid black
}

body>* {
      float: left;
}
</style>
</head>
<body>
      <canvas id="canvas" width="800" height="820"> 
      Your browser doesn't support the <code>canvas</code> element 
      </canvas>
      <script>
            var ctx = document.getElementById("canvas").getContext("2d");
            ctx.fillStyle = "lightgrey";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 3;
            ctx.font = "100px sans-serif";
            ctx.fillText("java2s.com", 10, 100);
            ctx.strokeText("java2s.com", 10, 100);
            ctx.fillStyle = "red";
            ctx.globalAlpha = 0.5;
            ctx.fillRect(100, 10, 150, 100);
      </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to change the stroke style
Home » Javascript Tutorial » Canvas
Canvas tag
Canvas Context
Rectangle
Rectangle clear
Drawing State
Drawing state restore
Line width
Line Join Style
Line cap settings
Gradients
Linear Gradient
Radial Gradient
Path
Arcs
Two types of curve
Quadratic Bezier Curves
Cubic Bezier Curves
Clip
Text
Shadow
Transparency
Stoke style