Published
Edited
Apr 14, 2022
1 fork
Insert cell
Insert cell
{
const svg = d3.create("svg")
.attr('width', width/2)
.attr("viewBox", "0 0 100 100");

svg.append("clipPath")
.attr("id", "myClip")
.append("circle") // Everything outside the circle will be clipped and therefore invisible.
.attr("cx", 40)
.attr("cy", 35)
.attr("r", 35);

// The original black heart, for reference
svg.append("path")
.attr("id", "heart")
.attr('d', heartPath); // "M10,30 A20,20,0,0,1,50,30 A20,20,0,0,1,90,30 Q90,60,50,90 Q10,60,10,30 Z"

// Only the portion of the red heart
// inside the clip circle is visible.
svg.append("use") // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use
.attr("clip-path", "url(#myClip)")
.attr("href", "#heart")
.attr("fill", "red");

return svg.node();
}
Insert cell
<style>
/* With a touch of CSS for browsers who *
* implemented the r Geometry Property. */

@keyframes openYourHeart {from {r: 0} to {r: 60px}}

#myClip circle {
animation: openYourHeart 15s infinite;
}
</style>
Insert cell
Insert cell
Insert cell
{
const svg = d3.create("svg")
.attr('width', width/2)
.attr("viewBox", "0 0 100 100");

const defs = svg.append("defs")
// the clipPath, whatever shape you want to be the mask
defs.append("clipPath")
.attr("id", "myClipV2")
.append("path")
.attr('d', heartPath); // heart shape

// only whatever parts of the shape inside the clipPath are visible
svg.append("circle")
.attr("clip-path", "url(#myClipV2)")
.attr("cx", 40)
.attr("cy", 35)
.attr("r", radius)
.attr("fill", "red");

// redrawing the heart so we can see the mask shape (not needed)
svg.append("path")
.attr('d', heartPath)
.attr("fill", "none")
.attr("stroke", "#ccc")
.attr("stroke-dasharray", "0.5, 0.5")
.attr("stroke-width", "0.5px");

return svg.node();
}
Insert cell
Insert cell
heartPath = "M10,30 A20,20,0,0,1,50,30 A20,20,0,0,1,90,30 Q90,60,50,90 Q10,60,10,30 Z"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more