简体   繁体   中英

the fillStyle of canvas is not working

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM