クリップ図形は円じゃなくても何でもいい。
クリップ図形とimageの位置を揃えるのがポイント。
- svgにdefsを追加
- defsにクリップ図形を追加
- defsにクリップパスを追加して、useで2の図形を指定
- imageにclip-pathで3を指定。
もし、imageが複数ある場合は、imageにあわせてクリップもつくる。
アニメーションで動かすときは、imageとあわせてクリップ図形も動かす。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>D3.jsでimageを円形にクリップ</title>
</head>
<body>
<div id="d3" style="width: 200px; height: 200px;"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var svg = d3.select('#d3')
.append('svg')
.attr('width', '100%')
.attr('height', '100%')
.style({
'background-color': 'rgba(255,255,250,1)'
});
// クリップする円の定義
var defs = svg.append('defs');
var circles = defs
.append('circle')
.attr('id', 'circle')
.attr('r', 50)
.attr('cx', 100)
.attr('cy', 100);
defs.append('clipPath')
.attr('id', 'clip')
.append('use')
.attr('xlink:href', '#circle');
// imageを描画
var images = svg
.append('image')
.attr('xlink:href', 'https://assets-cdn.github.com/images/modules/open_graph/github-octocat.png')
.attr('width', 100)
.attr('height', 100)
.attr('clip-path', 'url(#clip)')
.attr('x', 50)
.attr('y', 50);
</script>
</body>
</html>