鈍足ランナーのIT日記

走るのが好きな5流のITエンジニアのブログ。

趣味の範囲は広いけど、どれも中途半端なクソブロガー楽しめるWebアプリを作ってあっと言わせたい。サーバーサイドPerl(Mojolicious)、クライアントサイドVue.js。Arduinoにも触手を伸ばす予定。

React.js+ inline svgでクリックされた座標をうまいこと処理したい

React.jsでお絵かきみたいなことをしたいのだけど。

<title>Hello world</title>
<svg viewBox="0 0 500 500">
    <circle onClick={this.handleClick} cx="250" cy="250" r="250" fill="yellow" stroke="orange" />
</svg>

React.jsでこんな塩梅でクリック座標をとるのだが、
htmlのtitle部分のheightも加わった座標が返ってきてしまうので
やりずらい。title部分のheightをどうやって求めるのかがわからない。
円の上部をクリックしてもY座標は0が返ってこないのです。

  handleClick: function(event){
    console.log(event.clientX);
    console.log(event.clientY);
    console.log(event.screenX);
    console.log(event.screenY);
    console.log(event.pageX);
    console.log(event.pageY);
  },

以下を参考にしてみよう。

qiita.com
http://jsdo.it/defghi1977/q1VN


変換されない。うまく動かないなー。

  handleClick: function(event){
    var p, m;

    p = document.getElementById("svg").createSVGPoint();
    p.x = event.clientX;
    p.y = event.clientY;

    m = document.getElementById("circle").getScreenCTM();
    p.matrixTransform(m.inverse());

    console.log(event.clientX);
    console.log(event.clientY);
    console.log(p.x);
    console.log(p.y);
  }

だめだぁ。
これで試す。

tmlife.io

これはOK

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>   
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>  
</head>  
<body>    
<script type="text/jsx">      
var CommentBox = React.createClass({
  getInitialState: function(){
    return {x:0, y:0}
  },
  render: function() {
    return (
      <svg width="500" height="500" onClick={this.handleClick}>
        <rect width="10" height="10" x={this.state.x} y={this.state.y} />
      </svg>
    );
  },
  handleClick:function(e){
    this.setState({x: e.clientX,y: e.clientY});
  }
});
React.render(<CommentBox />, document.body);
</script>
</body>
</html>

これダメ

viewBoxをつかうとNG

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>   
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>  
</head>  
<body>    
<script type="text/jsx">      
var CommentBox = React.createClass({
  getInitialState: function(){
    return {x:0, y:0}
  },
  render: function() {
    return (
      <svg viewBox="0 0 500 500" onClick={this.handleClick}>
        <rect width="10" height="10" x={this.state.x} y={this.state.y} />
      </svg>
    );
  },
  handleClick:function(e){
    this.setState({x: e.clientX,y: e.clientY});
  }
});
React.render(<CommentBox />, document.body);
</script>
</body>
</html>