Skip to content

Instantly share code, notes, and snippets.

@shimizu shimizu/.block
Last active Mar 7, 2018

Embed
What would you like to do?
SVG Mask Example
license: mit
height: 0
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta http-equiv="content-language" content="ja">
<title>D3 circle Mask</title>
<script src="//unpkg.com/d3@4.12.2/build/d3.min.js"></script>
<style>
body {
background-image : url("p5.png");
}
svg {
width:100%;
height: 180px;
}
.wrapper {
float:right;
}
</style>
</head>
<body>
<div>
<div class="wrapper">
<p>mask</p>
<svg id="svg3"></svg>
</div>
<div class="wrapper">
<p>fill-opacity:0.5</p>
<svg id="svg2"></svg>
</div>
<div class="wrapper">
<p>default</p>
<svg id="svg1"></svg>
</div>
</div>
<script>
const dataSet =[
{r:20, color:"blue"},
{r:40, color:"red"},
{r:60, color:"blue"},
]
/*default*/
const svg1 = d3.select("#svg1")
svg1.selectAll("circle")
.data(dataSet.reverse())
.enter()
.append("circle")
.attr("cx", 100)
.attr("cy", 60)
.attr("r", d => d.r)
.attr("fill", d => d.color)
/*fill-opacity:0.5*/
const svg2 = d3.select("#svg2")
svg2.selectAll("circle")
.data(dataSet.reverse())
.enter()
.append("circle")
.attr("cx", 100)
.attr("cy", 60)
.attr("r", d => d.r)
.attr("fill", d => d.color)
.attr("fill-opacity", 0.5)
/*mask*/
const svg3 = d3.select("#svg3")
svg3.selectAll("circle")
.data(dataSet)
.enter()
.append("circle")
.attr("cx", 100)
.attr("cy", 60)
.attr("r", d => d.r)
.attr("fill", d => d.color)
.attr("fill-opacity", 0.5)
.attr("mask", (d, i) => {
if(i <= 0) return null;
return `url(#mask${i}`;
})
//部品の定義
const defs = svg3.append("defs");
dataSet.forEach(function(d, i){
if (i <= 0) return;
//defs内にmask要素を追加
const mask = defs.append("mask")
.attr("id", `mask${i}`);
//mask表示領域の指定
mask.append("circle")
.attr("cx", 100)
.attr("cy", 60)
.attr("r", dataSet[i].r)
.attr("fill", "white")
//mask非表示領域の指定
mask.append("circle")
.attr("cx", 100)
.attr("cy", 60)
.attr("fill", "black")
.attr("r", dataSet[i-1].r)
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.