Html HTML5 - 更改绘制矩形的不透明度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10487882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:14:23  来源:igfitidea点击:

HTML5 - Change opacity of a draw Rectangle

htmlcanvas

提问by test

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

假设我使用这个绘制了一个矩形的 HTML5 元素:

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

How would I make it 50% transparent?

我怎样才能让它 50% 透明?

回答by Brian Barnes

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:

ClearRect 删除那里的内容并将其留空。最好的方法是使用 rgba fillStyle 值,因为它只会使矩形(或您正在绘制的任何其他形状)透明。代码将是:

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?)

(感谢如何在绘制后更改画布元素中元素的不透明度(alpha,透明度)?

回答by Fábio Santos

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.

使用 globalAlpha。您还必须使用fillRect 进行绘制。clearRect 只是擦除像素。它不能部分擦除,因此您必须使用 fillRect 或其他绘图基元。

from w3schools.com:

来自w3schools.com

    ctx.globalAlpha = 0.2;
    ctx.fillRect(50,50,75,50);
    ctx.globalAlpha = 1.0;