How to set color to transparency when drawing on canvas

Description

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

Example


<!--from   w w  w.jav  a  2 s.  co  m-->
<!DOCTYPE HTML>
<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





















Home »
  Javascript »
    Javascript Reference »




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