SVG Image Mask
Details
- This example shows how to make a transparent hole in one image to show an image below it
- The process is to make a mask with two rectangles in it. One white, one black.
- The white rectangle defines the area that will show. Anything that's black is transparent.
- Since the black comes after the white it's on top which means it makes the area transparent
- The background image is placed before the foreground in the code which means it's behind it
- By applying the mask to the foreground image with url(#main-mask) the background image shows through where the transparency is
- The example below is built directly from the HTML and JavaScript code snippets that follow
EXAMPLE
HTML Source
<svg width="300" height="300"
viewBox="0 0 300 300"
xmlns="http://www.w3.org/2000/svg">
<mask id="main-mask">
<rect fill="white" width="300"
height="300" rx="20" x="0" y="0"/>
<rect fill="black" width="100"
height="100" rx="20" x="30" y="30"/>
</mask>
<image href="background.jpg" width="100"
height="100" x="30" y="30" />
<image href="foreground.jpg" mask="url(#main-mask)"
width="300" height="300" x="0" y="0" />
</svg>
JavaScript Source
const init = () => {
console.log('init')
console.log(c.alfa)
}
document.addEventListener('DOMContentLoaded', init)
JSON Data Source
{
"note": "Example JSON data file"
}
Config JS Source
// This file can be used to represent
// and data that should be held outside
// of the main script
const c = {
alfa: 'bravo',
}