5
3

More than 5 years have passed since last update.

D3.jsのimageを円形にクリップ

Posted at

クリップ図形は円じゃなくても何でもいい。
クリップ図形とimageの位置を揃えるのがポイント。

  1. svgにdefsを追加
  2. defsにクリップ図形を追加
  3. defsにクリップパスを追加して、useで2の図形を指定
  4. 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>

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3