绘制后如何更改画布元素中元素的不透明度

绘制后如何更改画布元素中元素的不透明度

本文介绍了绘制后如何更改画布元素中元素的不透明度(alpha,透明度)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 HTML5 元素,我想加载一个图像文件(PNG、JPEG 等),将其完全透明地绘制到画布上,然后淡入.我已经弄清楚如何加载图像并将其绘制到画布上,但我不知道如何在绘制后更改其不透明度.

Using the HTML5 <canvas> element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it in. I have figured out how to load the image and draw it to the canvas, but I don't know how to change its opacity once it as been drawn.

这是我目前的代码:

var canvas = document.getElementById('myCanvas');

if (canvas.getContext)
{
    var c           = canvas.getContext('2d');
    c.globalAlpha   = 0;

    var img     = new Image();
    img.onload  = function() {
        c.drawImage(img, 0, 0);
    }
    img.src     = 'image.jpg';
}

有人能指出我正确的方向吗,比如要设置的属性或要调用的函数会改变不透明度?

Will somebody please point me in the right direction like a property to set or a function to call that will change the opacity?

推荐答案

我也在寻找这个问题的答案,(澄清一下,我希望能够绘制具有用户定义不透明度的图像,例如您如何使用不透明度绘制形状)如果您使用原始形状绘制,您可以使用 alpha 设置填充和描边颜色来定义透明度.就我现在的结论而言,这似乎不会影响图像绘制.

I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.

//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";

我得出结论,设置 globalCompositeOperation 可以处理图像.

I have concluded that setting the globalCompositeOperation works with images.

//works with images
ctx.globalCompositeOperation = "lighter";

我想知道是否有某种第三种设置颜色的方法,以便我们可以轻松地为图像着色并使其透明.

I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.

经过进一步挖掘,我得出结论,您可以在绘制图像之前通过设置 globalAlpha 参数来设置图像的透明度:

After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image:

//works with images
ctx.globalAlpha = 0.5

如果你想随着时间的推移实现淡入淡出的效果,你需要某种改变 alpha 值的循环,这很容易,实现它的一种方法是 setTimeout 函数,查找创建一个循环,从中您可以随时间改变 alpha.

If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout function, look that up to create a loop from which you alter the alpha over time.

这篇关于绘制后如何更改画布元素中元素的不透明度(alpha,透明度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:30