问题
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