How to draw text with opacity in canvas?

Member

by denis , in category: Javascript , 4 months ago

How to draw text with opacity in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 4 months ago

@denis 

To draw text with opacity in HTML5 canvas, you can achieve this by setting the globalAlpha property of the canvas context to the desired opacity value before drawing the text. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Get the canvas element
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Set the opacity value
ctx.globalAlpha = 0.5; // Set opacity to 50%

// Draw text with opacity
ctx.font = "30px Arial";
ctx.fillText("Hello World", 50, 50);

// Reset the opacity value back to 1 (full opacity)
ctx.globalAlpha = 1;


In this example, the globalAlpha property is set to 0.5, which means the text will be drawn with 50% opacity. You can adjust this value to have different levels of opacity in your text. Remember to reset the globalAlpha value back to 1 if you want to draw other elements with full opacity.