HTML and CSS Reference
In-Depth Information
Transparency
Until now, all the graphic objects drawn on a canvas have been totally opaque. You can, however, change
the transparency of a graphic object using the strokeStyle and illStyle properties. These properties let
you set the color of a graphic such that in addition to RGB components, it also specifies a transparency
level. This is accomplished using the rgba() function (instead of more commonly used rgb() function).
Listing 4-15 shows how.
Listing 4-15. Setting the Transparency of a Drawing Object
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
context.fillStyle = "black";
context.fillRect(20, 20, 150, 80);
context.fillStyle = "rgb(255, 0, 0)";
context.fillRect(40, 40, 150, 80);
context.fillStyle = "black";
context.fillRect(20, 150, 150, 80);
context.fillStyle = "rgba(255, 0, 0,0.5)";
context.fillRect(40, 170, 150, 80);
The first block of code draws two filled rectangles without any transparency. The second block of code
draws two filled rectangles, with the second rectangle having a transparency of 50%. Notice how the rgba()
function is used. The fourth parameter of rgba() —the alpha value—controls the transparency. The alpha
value can be between 0 to 1, 0 being transparent and 1 being opaque. Figure 4-17 shows how both sets of
rectangle are rendered.
Figure 4-17. Controlling the opacity of drawing objects
 
Search WWH ::




Custom Search