previous next contents properties index

# 14 Clipping, Masking and Compositing

### Contents

## 14.1 Introduction

SVG supports the following clipping/masking features:

- clipping paths, which uses any combination of 'path', 'text' and basic shapes to serve as the outline of a (in the absense of antialiasing) 1-bit mask, where everything on the "inside" of the outline is allowed to show through but everything on the outside is masked out
- masks, which are container elements which can contain graphics elements or other container elements which define a set of graphics that is to be used as a semi-transparent mask for compositing foreground objects into the current background.

One key distinction between a clipping path and a mask is that clipping paths are hard masks (i.e., the silhouette consists of either fully opaque pixels or fully transparent pixels, with the possible exception of antialiasing along the edge of the silhouette) whereas masks consist of an image where each pixel value indicates the degree of transparency vs. opacity. In a mask, each pixel value can range from fully transparent to fully opaque.

SVG supports only simple alpha blending compositing (see Simple Alpha Blending/Compositing).

(Insert drawings showing a clipping path, a grayscale imagemask, simple alpha blending and more complex blending.)

## 14.2 Simple alpha blending/compositing

Graphics elements are blended into the elements already rendered on the canvas using simple alpha blending/compositing, in which the resulting color and opacity at any given pixel on the canvas is the result of the following formulas (all color values use premultiplied alpha):

    Er, Eg, Eb    - Element color value
    Ea            - Element opacity/alpha value
    Cr, Cg, Cb    - Canvas color value (before blending)
    Ca            - Canvas opacity/alpha value (before blending)
    Cr', Cg', Cb' - Canvas color value (after blending)
    Ca'           - Canvas opacity/alpha value (after blending)

    Ca' = 1 - (1 - Ea) * (1 - Ca)
    Cr' = (1 - Ea) * Cr + Er
    Cg' = (1 - Ea) * Cg + Eg
    Cb' = (1 - Ea) * Cb + Eb

The following rendering properties, which provide information about the color space in which to perform the compositing operations, apply to compositing operations:

- 'color-interpolation'
- 'color-rendering'

## 14.3 Clipping paths

### 14.3.1 Introduction

The clipping path restricts the region to which paint can be applied. Conceptually, any parts of the drawing that lie outside of the region bounded by the currently active clipping path are not drawn. A clipping path can be thought of as a 1-bit mask.

### 14.3.2 The initial clipping path

When an 'svg' element is encountered by a CSS user agent, the CSS user agent needs to establish an initial clipping path for the SVG document fragment. The 'overflow' and 'clip' properties from CSS2 along with additional SVG user agent processing rules determine the initial clipping path which the CSS user agent establishes for the SVG document fragment:

### 14.3.3 The 'overflow' and 'clip' properties

'overflow'

  Value: | visible | hidden | scroll | auto | inherit
  Initial: | visible (see notes below)
  Applies to: | elements which establish a new viewport
  Inherited: | no
  Percentages: | N/A
  Media: | visual
  Animatable: | N/A

The 'overflow' property has the same parameter values and has the same meaning as defined in [CSS2-overflow]; however, the following additional points apply:

- The 'overflow' property only applies to elements that establish new viewports, such as 'svg' elements. (See the discussion of the elements which establish a new viewport.)
- When an outermost SVG 'svg' element is embedded inline within a parent XML grammar which uses CSS layout [CSS2-LAYOUT] or XSL formatting [XSL], if the 'overflow' property has the value hidden, then the SVG user agent will establish an initial clipping path equal to the bounds of the initial viewport; otherwise, the initial clipping path is set according to the clipping rules as defined in [CSS2-overflow].
- When an outermost SVG 'svg' element is standalone or embedded inline within a parent XML grammar which does not use CSS layout [CSS2-LAYOUT] or XSL formatting [XSL], the 'overflow' property on the outermost 'svg' element is ignored for the purposes of visual rendering and the initial clipping path is set to the bounds of the initial viewport.
- For 'svg' elements that are embedded inside of an ancestor SVG document fragment (i.e., without a 'foreignObject' element between the inner 'svg' and the nearest ancestor 'svg') or for any other elements which establish a new viewport, the 'overflow' property determines whether an additional new clipping path is established around the bounds of the viewport established by the given element. If the value of the the 'overflow' property is hidden, then a new clipping path is established; otherwise, no new clipping path is established.
- The initial value for 'overflow' as defined in [CSS2-overflow] is 'visible'; however, the Default styles sheet for SVG specifies that the 'overflow' property on all elements within an SVG document fragment has the value 'hidden'.

As a result of the above, the default behavior of SVG user agents is to establish a clipping path to the bounds of the initial viewport and to establish a new clipping path for each element which establishes a new viewport.

For stand-alone SVG viewers or in situations where an SVG document fragment is embedded inline within a parent XML grammar which does not use CSS layout or XSL formatting, then the initial clipping path must be set to the bounds of the viewing region in which the SVG document fragment is rendered, even if the and the 'overflow' property is set to a value other than hidden.

For related information, see Clip to viewport vs. clip to viewBox.

'clip'

  Value: | <shape> | auto | inherit
  Initial: | auto
  Applies to: | elements which establish a new viewport
  Inherited: | no
  Percentages: | N/A
  Media: | visual
  Animatable: | N/A

The 'clip' property only applies to elements which establish a new viewport. The 'clip' property has the same parameter values as defined in [CSS2-clip]. Unitless values, which indicates current user coordinates, are permitted on the coordinate values on the <shape>. The value of "auto" defines a clipping path along the bounds of the viewport created by the given element.

### 14.3.4 Clip to viewport vs. clip to viewBox

It is important to note that initial values for the 'overflow' and 'clip' properties and the Default style sheet for SVG will result in an initial clipping path that is set to the bounds of the initial viewport. When attributes viewBox and preserveAspectRatio attributes are specified on a viewport-creating element, it is sometime desirable that the initial viewport be set to the bounds of the viewBox instead of the viewport, particularly when preserveAspectRatio specifies uniform scaling and the aspect ratio of the viewBox does not match the aspect ratio of the viewport.

To set the initial clipping path to the bounds of the viewBox instead of the viewport, set the bounds of 'clip' property to the same rectangle as specified on the viewBox attribute. (Note that the parameters don't match. 'clip' takes values <top>, <right>,<bottom> and <left>, whereas viewBox takes values <min-x>, <min-y>, <width> and <height>.)

### 14.3.5 Establishing a new clipping path

A clipping path is defined with a 'clipPath' element. A clipping path is used/referenced using the 'clip-path' property.

A 'clipPath' element can contain 'path' elements, 'text' elements, other vector graphic shapes (such as 'circle') or a 'use' element. If a 'use' element is a child of a 'clipPath' element, it must directly reference path, text or vector graphic shape elements. Indirect references are an error (see Error processing). The silhouettes of the child elements are logically OR'd together to create a single silhouette which is then used to restrict the region onto which paint can be applied.

It is an error if the 'clip-path' property references a non-existent object or if the referenced object is not a 'clipPath' element (see Error processing).

For a given graphics element, the actual clipping path used will be the intersection of the clipping path specified by its 'clip-path' property (if any) with any clipping paths on its ancestors, as specified by the 'clip-path' property on the ancestor elements.

A couple of notes:

- The 'clipPath' element itself and its child elements do not inherit clipping paths from the ancesotors of the 'clipPath' element.
- The 'clipPath' element or any of its children can specify property 'clip-path'.
  If a valid 'clip-path' reference is placed on a 'clipPath' element, the resulting clipping path is the intersection of the contents of the 'clipPath' element with the referenced clipping path.
  If a valid 'clip-path' reference is placed on one of the children of a 'clipPath' element, then the given child element is clipped by the referenced clipping path before OR'ing the silhouette of the child element with the silhouettes of the other child elements.

    <!ENTITY % clipPathExt "" >
    <!ELEMENT clipPath (%descTitle;,
                        (path|text|rect|circle|ellipse|line|polyline|polygon|
                         use|animate|set|animateMotion|animateColor|animateTransform
                         %ceExt;%clipPathExt;)*) >
    <!ATTLIST clipPath
      %stdAttrs;
      %langSpaceAttrs;
      class %ClassList; #IMPLIED
      transform %TransformList; #IMPLIED
      %testAttrs;
      externalResourcesRequired %Boolean; #IMPLIED
      clipPathUnits (userSpace | userSpaceOnUse | objectBoundingBox) "userSpace"
      %StylableSVG-StyleAttribute;
      %FinalFormSVG-ContainerAttrs;
      %FinalFormSVG-FillStrokeAttrs;
      %FinalFormSVG-GradientAttrs;
      %FinalFormSVG-GraphicsAttrs;
      %FinalFormSVG-MarkerAttrs;
      %FinalFormSVG-TextContainerAttrs;
      %FinalFormSVG-TextElementAttrs; >

Attribute definitions:

clipPathUnits = "userSpace | userSpaceOnUse | objectBoundingBox"
  Defines the coordinate system for the contents of the 'clipPath'.
  If clipPathUnits="userSpace" (the default), the contents of the 'clipPath' represent values in the current user coordinate system in place at the time when the 'clipPath' element is defined.
  If clipPathUnits="userSpaceOnUse", the contents of the 'clipPath' represent values in the current user coordinate system in place at the time when the 'clipPath' element is referenced (i.e., the user coordinate system for the element referencing the 'clipPath' element via the 'clip-path' property).
  If clipPathUnits="objectBoundingBox", the contents of the 'clipPath' represent values in the abstract coordinate system where (0,0) is the (minx,miny) in user space of the tight bounding box of the object referencing the mask, and (1,1) is the (maxx,maxy) corner of the bounding box. (Note: the bounding box represents the maximum extent of the shape of the object in X and Y with respect to the user coordinate system of the object exclusive of stroke-width.)
  Animatable: yes.

Attributes defined elsewhere:
  %stdAttrs;, %langSpaceAttrs;, %StylableSVG-StyleAttribute;.

'clip-path'

  Value: | <uri> | none | inherit
  Initial: | See The initial clipping path: 'overflow' and 'clip' properties
  Applies to: | all elements
  Inherited: | no
  Percentages: | N/A
  Media: | visual
  Animatable: | yes

<uri>
  A URI reference to another graphical object within the same SVG document fragment which will be used as the clipping path.

'clip-rule'

  Value: | evenodd | nonzero | inherit
  Initial: | evenodd
  Applies to: | all elements
  Inherited: | yes
  Percentages: | N/A
  Media: | visual
  Animatable: | yes

evenodd
nonzero

## 14.4 Masking

In SVG, you can specify that any other graphics object or 'g' element can be used as an alpha mask for compositing the current object into the background.

A mask is defined with a 'mask' element. A mask is used/referenced using the 'mask' property.

A 'mask' can contain any graphical elements or grouping elements such as a 'g'.

It is an error if the 'mask' property references a non-existent object or if the referenced object is not a 'mask' element (see Error Processing).

The effect is as if the child elements of the 'mask' are rendered into an offscreen image. Any graphical object which uses/references the given 'mask' element will be painted onto the background through the mask, thus completely or partially masking out parts of the graphical object.

The following processing rules apply:

- If all of the child elements of the 'mask' consist of the same type of one-channel image (i.e., a grayscale image or an image consisting only of an alpha channel), then the child elements will be processed as single channel images into a resulting single channel image result, and that single channel result will be used as the mask.
- If all of the child elements of the 'mask' consist of three-channel RGB images, then the child elements will be processed as RGB images into a resulting RGB image result, and the luminance from the resulting RGB image will be used as the mask, where the luminance is calculated using the luminance-to-alpha formulas as defined in the 'feColorMatrix' filter effect.
- Otherwise, the child elements of the 'mask' will be processed and will result in a four-channel RGBA image, and the alpha channel from this resulting RGBA image will be used as the mask.

Note that SVG 'path''s, shapes (e.g., 'circle') and 'text' are all treated as four-channel RGBA images for the purposes of masking operations.

In the following example, an image is used to mask a rectangle:

    <?xml version="1.0" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000302 Stylable//EN"
      "http://www.w3.org/TR/WD-SVG-20000302/DTD/svg-20000302-stylable.dtd">
    <svg width="4in" height="3in">
      <desc>Example of using a mask
      </desc>
      <g>
        <defs>
          <mask id="MyMask">
            <image xlink:href="transp.png" />
          </mask>
        </defs>
        <rect style="mask: url(#MyMask)" width="12.5" height="30" />
      </g>
    </svg>

Download this example

A <mask> element can define a region on the canvas for the mask using the following attributes:

    <!ENTITY % maskExt "" >
    <!ELEMENT mask (%descTitleDefs;,
                        (path|text|rect|circle|ellipse|line|polyline|polygon|
                         use|image|svg|g|switch|a|
                         animate|set|animateMotion|animateColor|animateTransform
                         %ceExt;%maskExt;)*) >
    <!ATTLIST mask
      %stdAttrs;
      %langSpaceAttrs;
      class %ClassList; #IMPLIED
      transform %TransformList; #IMPLIED
      %testAttrs;
      externalResourcesRequired %Boolean; #IMPLIED
      maskUnits (userSpace | userSpaceOnUse | objectBoundingBox) "userSpace"
      x %Coordinate; #IMPLIED
      y %Coordinate; #IMPLIED
      width %Length; #IMPLIED
      height %Length; #IMPLIED
      %StylableSVG-StyleAttribute;
      %FinalFormSVG-ContainerAttrs;
      %FinalFormSVG-FillStrokeAttrs;
      %FinalFormSVG-GradientAttrs;
      %FinalFormSVG-GraphicsAttrs;
      %FinalFormSVG-MarkerAttrs;
      %FinalFormSVG-TextContainerAttrs;
      %FinalFormSVG-TextElementAttrs;
      %FinalFormSVG-ViewportAttrs; >

Attribute definitions:

maskUnits = "userSpace | userSpaceOnUse | objectBoundingBox"
  Defines the coordinate system for attributes x, y, width, height and the contents of the 'mask'.
  If maskUnits="userSpace" (the default), x, y, width, height and the contents of the 'mask' represent values in the current user coordinate system in place at the time when the 'mask' element is defined.
  If maskUnits="userSpaceOnUse", x, y, width, height and the contents of the 'mask' represent values in the current user coordinate system in place at the time when the 'mask' element is referenced (i.e., the user coordinate system for the element referencing the 'mask' element via the 'mask' property).
  If maskUnits="objectBoundingBox", x, y, width, height and the contents of the 'mask' represent values in the abstract coordinate system where (0,0) is the (minx,miny) in user space of the tight bounding box of the object referencing the mask, and (1,1) is the (maxx,maxy) corner of the bounding box. (Note: the bounding box represents the maximum extent of the shape of the object in X and Y with respect to the user coordinate system of the object exclusive of stroke-width.)
  Animatable: yes.
x = "<coordinate>"
  The x coordinate of one corner of the rectangle for the largest possible offscreen buffer, where the values are either relative to the current user coordinate system (if maskUnits="userSpace") or relative to the current object (if maskUnits="objectBoundingBox"). Note that the clipping path used to render any graphics within the mask will consists of the intersection of the current clipping path associated with the given object and the rectangle defined by x, y, width, height. The default value for x is 0%.
  Animatable: yes.
y = "<coordinate>"
  The y coordinate of one corner of the rectangle for the largest possible offscreen buffer.The default value for y is 0%.
  Animatable: yes.
width = "<length>"
  The width of the largest possible offscreen buffer, where the values are either relative to the current user coordinate system (if maskUnits="userSpace") or relative to the current object (if maskUnits="objectBoundingBox"). Note that the clipping path used to render any graphics within the mask will consists of the intersection of the current clipping path associated with the given object and the rectangle defined by x, y, width, height. The default value for width is 100%.
  Animatable: yes.
height = "<length>"
  The height of the largest possible offscreen buffer. The default value for height is 100%.
  Animatable: yes.

Attributes defined elsewhere:
  %stdAttrs;, %langSpaceAttrs;, %StylableSVG-StyleAttribute;.

The following is a description of the 'mask' property.

'mask'

  Value: | <uri> | none | inherit
  Initial: | none
  Applies to: | all elements
  Inherited: | no
  Percentages: | N/A
  Media: | visual
  Animatable: | yes

<uri>
  A URI reference to another graphical object which will be used as the mask.

## 14.5 Object and group opacity: the 'opacity' property

There are several opacity properties within SVG:

- Fill opacity
- Stroke opacity
- Gradient stop opacity
- Object/group opacity (described here)

Except for object/group opacity (described just below), all other opacity properties are involved in intermediate rendering operations. Object/group opacity can be thought of conceptually as a postprocessing operation. Conceptually, after the object/group is rendered into an RGBA offscreen image, the object/group opacity setting specifies how to blend the offscreen image into the current background.

'opacity'

  Value: | <alphavalue> | inherit
  Initial: | 1
  Applies to: | all elements
  Inherited: | no
  Percentages: | N/A
  Media: | visual
  Animatable: | yes

<alphavalue>
  The uniform opacity setting to be applied across an entire object. Any values outside the range 0.0 (fully transparent) to 1.0 (fully opaque) will be clamped to this range. (See Clamping values which are restricted to a particular range If the object is a container element such as a 'g', then the effect is as if the contents of the 'g' were blended against the current background using a mask where the value of each pixel of the mask is <alphavalue>. (See Simple alpha blending/compositing.)

Example opacity01, illustrates various usage of the 'opacity' property on elements and groups.

    <?xml version="1.0" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20000302 Stylable//EN"
      "http://www.w3.org/TR/WD-SVG-20000302/DTD/svg-20000302-stylable.dtd">
    <svg width="12cm" height="3.5cm">
      <desc>Example opacity01 - opacity property</desc>

      <!-- Background blue rectangle -->
      <rect x="1cm" y="1cm" width="10cm" height="1.5cm" style="fill:#0000ff" />

      <!-- Red circles going from opaque to nearly transparent -->
      <circle cx="2cm" cy="1cm" r=".5cm" style="fill:red; opacity:1" />
      <circle cx="4cm" cy="1cm" r=".5cm" style="fill:red; opacity:.8" />
      <circle cx="6cm" cy="1cm" r=".5cm" style="fill:red; opacity:.6" />
      <circle cx="8cm" cy="1cm" r=".5cm" style="fill:red; opacity:.4" />
      <circle cx="10cm" cy="1cm" r=".5cm" style="fill:red; opacity:.2" />

      <!-- Opaque group, opaque circles -->
      <g style="opacity:1">
        <circle cx="1.825cm" cy="2.5cm" r=".5cm" style="fill:red; opacity:1" />
        <circle cx="2.175cm" cy="2.5cm" r=".5cm" style="fill:green; opacity:1" />
      </g>
      <!-- Group opacity: .5, opacity circles -->
      <g style="opacity:.5">
        <circle cx="3.825cm" cy="2.5cm" r=".5cm" style="fill:red; opacity:1" />
        <circle cx="4.175cm" cy="2.5cm" r=".5cm" style="fill:green; opacity:1" />
      </g>
      <!-- Opaque group, semi-transparent green over red -->
      <g style="opacity:1">
        <circle cx="5.825cm" cy="2.5cm" r=".5cm" style="fill:red; opacity:.5" />
        <circle cx="6.175cm" cy="2.5cm" r=".5cm" style="fill:green; opacity:.5" />
      </g>
      <!-- Opaque group, semi-transparent red over green -->
      <g style="opacity:1">
        <circle cx="8.175cm" cy="2.5cm" r=".5cm" style="fill:green; opacity:.5" />
        <circle cx="7.825cm" cy="2.5cm" r=".5cm" style="fill:red; opacity:.5" />
      </g>
      <!-- Group opacity .5, semi-transparent green over red -->
      <g style="opacity:.5">
        <circle cx="10.175cm" cy="2.5cm" r=".5cm" style="fill:red; opacity:.5" />
        <circle cx="9.825cm" cy="2.5cm" r=".5cm" style="fill:green; opacity:.5" />
      </g>
    </svg>

Example opacity01

View this example as SVG (SVG-enabled browsers only)

In the example above, the top row of circles have differing opacities, ranging from 1.0 to 0.2. The bottom row illustrates five 'g' elements, each of which contains overlapping red and green circles, as follows:

- The first group shows the opaque case for reference. The group has opacity of 1, as do the circles.
- The second group shows group opacity when the elements in the group are opaque.
- The third and fourth group show that opacity is not commutative. In the third group (which has opacity of 1), a semi-transparent green circle is drawn on top of a semi-transparent red circle, whereas in the fourth group a semi-transparent red circle is drawn on top of a semi-transparent green circle. Note that area where the two circles intersect display different colors. The third group shows more green color in the intersection area, whereas the fourth group shows more red color.
- The fifth group shows the multiplicative effect of opacity settings. Both the circles and the group itself have opacity settings of .5. The result is that the portion of the red circle which does not overlap with the green circle (i.e., the top/right of the red circle) will blend into the blue rectangle with accumulative opacity of .25 (i.e., .5*.5), which, after blending into the blue rectangle, results in a blended color which is 25% red and 75% blue.

## 14.6 DOM interfaces

The following interfaces are defined below: SVGClipPathElement, SVGMaskElement.

### Interface SVGClipPathElement

The SVGClipPathElement interface corresponds to the 'clipPath' element.

IDL Definition

      interface SVGClipPathElement : SVGElement, SVGLangSpace, SVGUnitTypes {
                 attribute DOMString className;
                 attribute unsigned short clipPathUnits;

      #ifdef STYLABLESVG
                 // The following pre-defined attribute collections are only
                 // available in the DOM for Stylable SVG.
                 STYLABLESVGStyleAttribute;
      #endif STYLABLESVG

      #ifdef FINALFORMSVG
                 // The following pre-defined attribute collections are only
                 // available in the DOM for Final Form SVG.
                 FINALFORMSVGContainerAttrs;
                 FINALFORMSVGFillStrokeAttrs;
                 FINALFORMSVGGradientAttrs;
                 FINALFORMSVGGraphicsAttrs;
                 FINALFORMSVGMarkerAttrs;
                 FINALFORMSVGTextContainerAttrs;
                 FINALFORMSVGTextElementAttrs;
      #endif FINALFORMSVG
          };

Attributes
  DOMString className
    Corresponds to attribute class on the given element.
  unsigned short clipPathUnits
    Corresponds to attribute clipPathUnits on the given 'clipPath' element. Takes on one of the constants defined in SVGUnitTypes.

### Interface SVGMaskElement

The SVGMaskElement interface corresponds to the 'mask' element.

IDL Definition

      interface SVGMaskElement : SVGElement, SVGLangSpace, SVGUnitTypes {
                 attribute DOMString className;
                 attribute unsigned short maskUnits;
                 attribute SVGLength      x;
                 attribute SVGLength      y;
                 attribute SVGLength      width;
                 attribute SVGLength      height;

      #ifdef STYLABLESVG
                 // The following pre-defined attribute collections are only
                 // available in the DOM for Stylable SVG.
                 STYLABLESVGStyleAttribute;
      #endif STYLABLESVG

      #ifdef FINALFORMSVG
                 // The following pre-defined attribute collections are only
                 // available in the DOM for Final Form SVG.
                 FINALFORMSVGContainerAttrs;
                 FINALFORMSVGFillStrokeAttrs;
                 FINALFORMSVGGradientAttrs;
                 FINALFORMSVGGraphicsAttrs;
                 FINALFORMSVGMarkerAttrs;
                 FINALFORMSVGTextContainerAttrs;
                 FINALFORMSVGTextElementAttrs;
                 FINALFORMSVGViewportAttrs;
      #endif FINALFORMSVG
          };

Attributes
  DOMString className
    Corresponds to attribute class on the given element.
  unsigned short maskUnits
    Corresponds to attribute maskUnits on the given 'mask' element. Takes on one of the constants defined in SVGUnitTypes.
  SVGLength x
    Corresponds to attribute x on the given 'mask' element.
  SVGLength y
    Corresponds to attribute y on the given 'mask' element.
  SVGLength width
    Corresponds to attribute width on the given 'mask' element.
  SVGLength height
    Corresponds to attribute height on the given 'mask' element.

previous next contents properties index