V
V
Vladimir2017-06-16 19:35:45
Canvas
Vladimir, 2017-06-16 19:35:45

What's the best way to work with Canvas in React/Redux?

Tell me, how can I implement / simplify the work with canvas in react? After all, canvas mutates dom elements directly, while React renders data through a virtual dom.
For example, maybe there is some popular library or even a framework compatible with the React programming concept? thank.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2017-06-17
@vnam92

"canvas directly mutates dom elements" - it's not entirely clear what is meant. Drawing happens on the canvas. The house doesn't change, something inside the canvas changes. Therefore, in order to refer to this "canvas" (meaning the tag itself), we need ref. For example: <canvas ref='myCanvas' width={180} height={30} />.
The second question is also not entirely clear, what is meant by "concept and compatibility"? Since you have a reference to the "canvas" through this.refs.myCanvas, you can further pull out the context using getContext and continue to work.
An example of a component (depending on the received data, it draws columns higher, lower ..)

export default class SomeBars extends Component {
  componentDidMount() {
    this.drawBars(this.props)
  }
  drawBars(props) {
    const { data } = props
    const canvas = this.refs.canvas
    const ctx = canvas.getContext('2d')
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    const tempData = data ? data.slice(0,60) : []

    tempData.forEach((item,index) => {
      ctx.fillStyle = 'rgba(3,169,244,1)'
      ctx.fillRect(index*3, 30, 2, -(item/2))
    })
  }
  render() {
    return <canvas ref='canvas' width={180} height={30} />
  }
}

If we are talking about canvas and support for dragging the mouse and all sorts of cool things (for example, as fabric.js can do) - then you can read on SO
Also, Google, as usual, gives out several links, for example .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question