Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 - Change opacity of a draw Rectangle

Tags:

html

canvas

Let's say I draw an HTML5 element of rectangle using this:

context.clearRect(25, 72, 32, 32); 

How would I make it 50% transparent?

like image 716
test Avatar asked May 07 '12 19:05

test


People also ask

How do I make an opaque filled rectangle in HTML?

The fillRect() method draws a "filled" rectangle. The default color of the fill is black. Tip: Use the fillStyle property to set a color, gradient, or pattern used to fill the drawing.

How to set opacity of color in HTML?

Changing the opacity of the background color only To achieve this, use a color value which has an alpha channel—such as rgba. As with opacity , a value of 1 for the alpha channel value makes the color fully opaque. Therefore background-color: rgba(0,0,0,. 5); will set the background color to 50% opacity.

How to change opacity in canvas?

In the Canvas Layer Editor window (Windows > Editors > Canvas Layer Editor ), click on the image layer's and drag up (higher opacity) or down (lower opacity).

How do I make a transparent canvas in HTML?

The globalAlpha property returns the transparency value of drawing. The value 1.0 of this property specifies no transparency and the value 0.0 of this property specifies full transparency. Hence, by setting the globalAlpha property to 0.0, we can get a transparent canvas.


2 Answers

Use globalAlpha. You'll also have to draw with fillRect. clearRect just erases pixels. It can't partially erase so you'll have to use fillRect or other drawing primitives.

from w3schools.com:

    ctx.globalAlpha = 0.2;     ctx.fillRect(50,50,75,50);     ctx.globalAlpha = 1.0; 
like image 196
Fábio Santos Avatar answered Sep 21 '22 12:09

Fábio Santos


ClearRect removes what was there and leaves it blank. The best way is to use a rgba fillStyle value as it will only make the rectangle (or any other shape that you are drawing) transparent. The code would be:

ctx.fillStyle = 'rgba(225,225,225,0.5)'; ctx.fillRect(25,72,32,32); 

(thanks How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?)

like image 33
Brian Barnes Avatar answered Sep 18 '22 12:09

Brian Barnes