【问题标题】:the fillStyle of canvas is not working画布的填充样式不起作用
【发布时间】:2017-09-17 16:54:45
【问题描述】:

我有一个有循环的函数。在循环中它创建一个画布并设置不透明度。 然后它设置背景颜色并将画布转换为图像。

不知何故,在画布上设置了不透明度,但没有设置背景颜色。

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();
}

我不确定为什么没有设置我的背景。有什么建议吗?

提前谢谢你。

【问题讨论】:

  • 不透明度的值为 0.5 @moáois
  • 没有。不透明度工作正常。我希望背景颜色也可以工作。目前没有设置背景。所以图像应该同时具有不透明度和背景。 @moáois
  • 我现在的背景是黑色的

标签: javascript html canvas 2d 2d-context-api


【解决方案1】:

使用context.fillStyle = background,您无需设置画布的背景颜色。相反,它为画布设置绘图工具的填充颜色。

换句话说,context.fillStyle 仅适用于画布上绘制的线条或形状之后


要用颜色填充画布,请使用fillRect() 函数:

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

这个canvas cheat sheet被证明是有帮助的

【讨论】:

  • 我可以用什么来设置背景?在我的情况下,我应该使用什么? @Aloso
  • 如果您想用纯色填充画布,请使用fillRect() 函数绘制一个矩形。绘制时确保globalAlphafillStyle设置正确。
  • 如果你只想填充图像中透明的部分,你必须绘制矩形behind其他内容。这可以使用globalCompositeOperation 来实现。
  • 我现在的背景是黑色的。
猜你喜欢
  • 1970-01-01
  • 2012-11-14
  • 2013-09-07
  • 2012-01-22
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多