the fillStyle of canvas is not working

一曲冷凌霜 提交于 2019-12-12 04:31:42

问题


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.


回答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



来源:https://stackoverflow.com/questions/43529976/the-fillstyle-of-canvas-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!