Javascript – Rendering / Returning HTML5 Canvas in ReactJS

javascriptreactjs

I am trying to render a canvas using React. The graphics inside the canvas would also be handled by Reacts render method.

The current code does render a canvas with the graphics I want. But I am looking for a way to return a canvas with my graphics from within the render method. The reason I want this, is cause I want this to work in "React Way".

Ideally, I would want my code to be something like this:

return(
  <div>
    <canvas id='my_canvas_with_graphics_rendered_in_react'></canvas>
  </div>
);

First, I want to know if this is even possible. Or if I should look for an alternative.

Maybe Im missing the point of React, if that is the case please let me know. I do hope there is a solution, because from what I've read React touts itself as the V in MVC. That is why, if possible, this would be a perfect solution for what I'm trying to do. I would not have to worry about the rendering inside my canvas. I would simply supply the data to the component and React would re-render the changes.

I have marked of in the return statement where I believe the correct code should go.

The HTML code:

<div id='wrapper'>
    <canvas id='canvas'></canvas>
</div>

The jsx code:

var MyCanvas = React.createClass({
    render:function(){
        var line = this.props.lines;
        var ctx = this.props.canvas.getContext("2d");

        ctx.strokeStyle = 'rgba(0,0,0,0.5)';
        ctx.beginPath();
        ctx.moveTo(line[0].x0, line[0].y0);
        // .... more code .....
        ctx.stroke();

        return(
            <div>
                /* *********************************
                ??? RETURN MY RENDERED CANVAS
                    WITH GRAPHIC LINES. ????
             This is where I want to return the canvas 
                *********************************  */
            </div>
        );

    }
});


var wrapper = document.getElementById('wrapper');
var canvas = document.getElementById('canvas');
var line1 = { x0: 0, y0: 10, x1: 20, y1: 30 };
var line2 = { x0: 40, y0: 50, x1: 60, y1: 70 };

var myCanvas = <MyCanvas canvas={ canvas } lines={ [line1, line2] } />;
React.render(myCanvas, wrapper);

Hope I made myself clear.

Best Solution

Your only error was that you were not familar with react refs. try this:

class ConnectionChart extends React.Component {

    componentDidMount() {
        let canvas = ReactDOM.findDOMNode(this.refs.myCanvas);
        let ctx = canvas.getContext('2d');

        ctx.fillStyle = 'rgb(200,0,0)';
        ctx.fillRect(10, 10, 55, 50);
    }

    render() {
        return (
            <div>
                <canvas ref="myCanvas" />
            </div>
        );
    }
}

You might have get rid of the ES6 style but you get the idea. Of cause u can paint in other methods too ^^