【问题标题】:Difference between canvas and SVG (fill effect)canvas和SVG的区别(填充效果)
【发布时间】:2019-04-04 21:16:46
【问题描述】:

我有一个关于画布和 SVG 的基本问题。我想创建一个带孔的叠加层并用一些颜色填充它。 它似乎可以使用画布,但我想尝试 SVG(处理事件,例如调整大小)。

canvas.width  = 200;
canvas.height = 200;

var context = canvas.getContext('2d');

//fill background
context.globalAlpha = 0.8;
context.fillStyle = "blue"
context.fillRect(0, 0, 200, 200);


context.globalCompositeOperation = 'xor';
context.globalAlpha = 1.0;
context.fillStyle = "rgba(0,0,0,1)";
context.fillRect(50, 50, 50, 50);

https://jsfiddle.net/gpx21/195ygzhq/

但 SVG 蒙版看起来太轻了。

<svg width="200" height="200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="
    position: absolute;
    z-index: 19000;
    top: 0;
    left: 0;
">
    <defs>
        <mask id="mask1" maskContentUnits="userSpaceOnUse">
            <rect x="0" y="0" width="200" height="200" style="opacity: 0.8; fill:blue;"></rect>
            <path d="M50 50 H100 V100 H50Z" id="hole"></path>
        </mask>
    </defs>
    <rect width="200" height="200" style="fill:blue; mix-blend-mode: darken;mask:url(#mask1);"></rect>
</svg>

https://jsfiddle.net/gpx21/1fktpnr5/

我怎样才能获得与画布相同的效果?谢谢。

【问题讨论】:

    标签: javascript css svg canvas


    【解决方案1】:

    您可以将 SVG 蒙版视为灰度图像。在该图像为白色的地方,被遮罩的元素是可见的,在它是黑色的地方,被遮罩的元素是透明的。

    因此,要获得半透明的蓝色&lt;rect&gt;,您可以应用大部分为浅灰色(即“几乎是白色”)的&lt;mask&gt;,除了会导致透明孔的黑色部分:

    <defs>
        <mask id="mask1" maskContentUnits="userSpaceOnUse">
            <rect x="0" y="0" width="200" height="200" fill="lightgray"></rect>
            <path d="M50 50 H100 V100 H50Z" id="hole" fill="black"></path>
        </mask>
    </defs>
    <rect width="200" height="200" style="fill:blue; mask:url('#mask1');"></rect>
    

    https://jsfiddle.net/1fktpnr5/1/

    【讨论】:

      【解决方案2】:

      这是一个简单的修复。当您在 svg 文档中定义遮罩时,可以为遮罩元素填充黑色以隐藏它们,填充白色以显示它们,或者介于两者之间以实现不同级别的透明度。 (source)

      在您的掩码代码中:

      <defs>
        <mask id="mask1" maskContentUnits="userSpaceOnUse">
          <rect x="0" y="0" width="200" height="200" style="opacity: 0.8; fill:blue;"></rect>
          <path d="M50 50 H100 V100 H50Z" id="hole"></path>
        </mask>
      </defs>
      

      您可以将fill:blue 更改为fill:white,这应该可以解决问题。

      【讨论】:

        猜你喜欢
        • 2018-10-12
        • 2011-06-27
        • 1970-01-01
        • 2022-01-02
        • 2020-07-10
        • 1970-01-01
        • 1970-01-01
        • 2013-03-07
        • 2019-09-21
        相关资源
        最近更新 更多