32
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Reactからcanvasを使って絵を書く

Last updated at Posted at 2018-08-08

canvas上に絵が書けるcomponentをReactで作ってみました。

ポイント

  • 書いている状態かどうかをstateで管理
  • contextの取得 this.refs.canvas.getContext('2d')
  • offsetX,offsetYnativeEventからアクセスする
  • canvasのwidth/heightはcssではなくHTMLのプロパティで指定する

コード

Canvas.js
import React, { Component } from 'react';

const style = {
  border: '1px solid gray',
  backgroundColor: 'white',
};

class Canvas extends Component {
  constructor() {
    super();
    this.state = { drawing: false };
  }

  getContext() {
    return this.refs.canvas.getContext('2d');
  }

  startDrawing(x, y) {
    this.setState({ drawing: true });
    const ctx = this.getContext();
    ctx.moveTo(x, y);
  }

  draw(x, y) {
    if (!this.state.drawing) {
      return;
    }
    const ctx = this.getContext();
    ctx.lineTo(x, y);
    ctx.stroke();
  }

  endDrawing() {
    this.setState({ drawing: false });
  }

  render() {
    return (
      <canvas
        ref="canvas"
        width="500px"
        height="500px"
        onMouseDown={e => this.startDrawing(e.nativeEvent.offsetX, e.nativeEvent.offsetY)}
        onMouseUp={() => this.endDrawing()}
        onMouseLeave={() => this.endDrawing()}
        onMouseMove={e => this.draw(e.nativeEvent.offsetX, e.nativeEvent.offsetY)}
        style={style}
      />
    );
  }
}
export default Canvas;
32
20
1

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
32
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?