如何使用 Python 的 svgwrite 模块应用 alpha 掩码?

Jon*_*ine 4 python svg

我正在使用svgwrite模块以编程方式为项目创建一些图像。我需要使用 alpha 蒙版来创建渐变的透明元素。我不清楚如何在创建后实际应用蒙版。

在下面的示例中,我尝试使用圆形渐变在其他灰色方块中创建渐变透明环。我可以创建正方形;我可以单独创建圆形渐变 def 和一个填充它的圆圈。

将一个应用到另一个作为面具我不明白。

def my_mask():
            #  define some params
            width = "500px"
            height = "500px"
            radius = "50%"
            black = "rgb(255, 255, 255)"
            grey = "rgb(127,127,127)"

            #  create the drawing surface
            canvas = svgwrite.Drawing('temp_mask.svg', (width, height))

            #  create defs, in this case, just a single gradient
            rad_grad = canvas.radialGradient(("50%", "50%"), "50%", ("50%", "50%"), id="rad_grad")
            rad_grad.add_stop_color("0%", black, 0)
            rad_grad.add_stop_color("66.6%", black, 255)
            rad_grad.add_stop_color("100%", black, 255)

            #  now to draw; first I create the rect object to be masked
            base_rect = canvas.rect( (0, 0), (width, height), id="masked_rect").fill(grey)
            canvas.add(base)
    
            #  and according to the docs, any SVG fragment can be an alpha mask, so I create this circle
            mask_element = canvas.circle((radius, radius), radius, fill="url(#rad_grad)")

            #  but here's where I get confused; I don't get how this function actually makes use of one element to mask another
            canvas.mask((0, 0), (width, height))

        #  No problem exporting to a file, though. :)
        canvas.save()
Run Code Online (Sandbox Code Playgroud)

这就是我所追求的(刚刚添加了红十字以展示透明度);用 Sketch 很容易做到 预期效果示例

Luk*_*uke 5

谢谢琼琳!ClipPath 和 Mask 的 svgwrite“示例”没有实际向您展示如何将其应用于绘图。为了完整起见,我使用您的方法为 ClipPath 编写了一个真实示例:

clip_path = dwg.defs.add(dwg.clipPath(id='my_clip_path1')) #name the clip path
clip_path.add(dwg.circle((5*mm, 5*mm), 10*mm)) #things inside this shape will be drawn
testCircle = dwg.add(dwg.g(id='test', stroke='red', stroke_width=1, fill='black', fill_opacity=1, clip_path="url(#my_clip_path1)"))
testCircle.add(dwg.circle((5*mm, 10*mm), 10*mm))
Run Code Online (Sandbox Code Playgroud)

此代码的结果