Can someone please explain why this doesn't work:
var MyImage = new Image();
MyImage.src = "SomeImage.png";
MyImage.style.opacity = 0.5; // has no effect
ctx.drawImage(MyImage,100,100); // shows image with 1.0 opacity
I'm using firefox. The image file loads and works fine, just the opacity is missing. I'd rather have a solution without JQuery. I'd also like to change the opacity in a loop, so I think I can't use a CSS - solution
EDIT: The solution is found behind the link above, thank you.
I thought I might as well write the solution here also, in case it helps someone with similar questions.
For image opacity I must change the context global alpha.
For example:
ctx.globalAlpha = 0.5;
ctx.drawImge(MyImg,X,Y);
ctx.globalAlpha = 1.0; // remember to reset the alpha value back to 1.0
For fade out effect on screen you can use an object like:
function ObjectToRender(Img, OpacityValue, X,Y){
this.Img = Img;
this.OpacityValue = OpacityValue;
this.X = X;
this.Y = Y;
}
then you can loop through the rendering, and drop the opacity by increments.
this example assumes that you have several obejcts like above to render, stored in an array "StuffToRender".
// call this every time you want to decrease the opacity for each image
for (var i=0; i<StuffToRender.length; i++){
StuffToRender[i].OpacityValue -= 0.05; // this can be set as you like
if (StuffToRender.OpacityValue > 0){
ctx.globalAlpha = StuffToRender[i].OpacityValue;
ctxdrawImage(StuffToRender[i].Img, StuffToRender[i].X,StuffToRender[i].Y);
} else {StuffToRender.splice(i,1);}
}
ctx.globaAlpha = 1;
the change in globalAlpha only affects image drawn after the change, not the ones drawn before. So, you can have several fade outs going on at the same time, with different opacities.
I also found some solutions with transparent div on top of the main Div, and the solution was to draw into the top layer div and change the alpha for that div only. Then one should change the Z-index of the divs or the dispaly mode. Changing these rapidly caused me some flickering, so I can't recommend that method. I don't know about the performance differences between these two ways.