0

i have a function that has a loop. in the loop it creates a canvas and sets the opacity. Then it sets the background color and converts the canvas to an image.

Somehow the Opacity is being set on the canvas but the background color doesn't get set.

if (remain <= 0) {
    var canvas = document.createElement('canvas');
    context = canvas.getContext('2d');
    for (var i = 0; i < img.length; ++i) {
        if (img[i]) {
         var opacity = item.opa;
         context.globalAlpha = opacity;
         context.drawImage(img[i],0,0);
        }
    }
    var background = mp.colbk; //returns rgb(255,0,0)
    context.fillStyle = background;
    var im = new Image();
    im.src = canvas.toDataURL();
}

Im not sure why my background is not being set. any suggestions?

Thank you in advance.

  • the value for opacity is 0.5 @moáois –  Apr 20 '17 at 21:16
  • No. Opacity is working fine. i want the background color to work too. there is currently no background being set. So the image should have both opacity and background. @moáois –  Apr 20 '17 at 21:19
  • im now i getting a black background –  Apr 20 '17 at 22:37

1 Answers1

1

With context.fillStyle = background, you are NOT setting the background color of the canvas. Instead, it sets the fill color of the drawing tool for the canvas.

In other words, context.fillStyle only applies to lines or shapes drawn on the canvas afterwards.


To fill the canvas with a color, use the fillRect() function:

context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);

This canvas cheat sheet proved to be helpful

Aloso
  • 5,123
  • 4
  • 24
  • 41
  • What can i use to set a background? in my case what should i be using then? @Aloso –  Apr 20 '17 at 21:20
  • If you want to fill the canvas with a solid color, draw a rectangle using the `fillRect()` function. Make sure that `globalAlpha` and `fillStyle` are set correctly when drawing it. – Aloso Apr 20 '17 at 21:22
  • If you only want to fill the parts of the image that are transparent, you have to draw the rectangle `behind` the other content. This can be achieved using `globalCompositeOperation`. – Aloso Apr 20 '17 at 21:25
  • i get a black background now. –  Apr 20 '17 at 22:37