<canvas>
very often. I have made some fairly complex web applications where canvas is the main element of the data view. Using canvas without any frameworks and libraries can be really difficult in large applications. So I started using frameworks a lot. Now I support the Konva framework (there is a review article https://habrahabr.ru/post/250897/ ). class CanvasComponent extends React.Component { componentDidMount() { this.updateCanvas(); } updateCanvas() { const ctx = this.refs.canvas.getContext('2d'); ctx.fillRect(0,0, 100, 100); } render() { return ( <canvas ref="canvas" width={300} height={300}/> ); } } ReactDOM.render(<CanvasComponent/>, document.getElementById('container'));
// , function rect(props) { const {ctx, x, y, width, height} = props; ctx.fillRect(x, y, width, height); } class CanvasComponent extends React.Component { componentDidMount() { this.updateCanvas(); } componentDidUpdate() { this.updateCanvas(); } updateCanvas() { const ctx = this.refs.canvas.getContext('2d'); ctx.clearRect(0,0, 300, 300); // "" rect({ctx, x: 10, y: 10, width: 50, height: 50}); rect({ctx, x: 110, y: 110, width: 50, height: 50}); } render() { return ( <canvas ref="canvas" width={300} height={300}/> ); } } ReactDOM.render(<CanvasComponent/>, document.getElementById('container'));
npm install react konva react-konva --save
import React from 'react'; import ReactDOM from 'react-dom'; import {Layer, Rect, Stage, Group} from 'react-konva'; class MyRect extends React.Component { constructor(...args) { super(...args); this.state = { color: 'green' }; this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ color: Konva.Util.getRandomColor() }); } render() { return ( <Rect x={10} y={10} width={50} height={50} fill={this.state.color} shadowBlur={10} onClick={this.handleClick} /> ); } } function App() { return ( <Stage width={700} height={700}> <Layer> <MyRect/> </Layer> </Stage> ); } ReactDOM.render(<App/>, document.getElementById('container'));
function MyShape() { return ( <Shape fill=”#00D2FF” draggable sceneFunc={function (ctx) { ctx.beginPath(); ctx.moveTo(20, 50); ctx.lineTo(220, 80); ctx.quadraticCurveTo(150, 100, 260, 170); ctx.closePath(); // Konva specific method ctx.fillStrokeShape(this); }} /> ); }
class MyCircle extends React.Component { constructor(…args) { super(…args); this.state = { isMouseInside: false}; this.handleMouseEnter = this.handleMouseEnter.bind(this); this.handleMouseLeave = this.handleMouseLeave.bind(this); } handleMouseEnter() { this.setState({ isMouseInside: true}); } handleMouseLeave() { this.setState({ isMouseInside: false}); } render() { return ( <Circle x={100} y={60} radius={50} fill=”yellow” stroke=”black” strokeWidth={this.state.isMouseInside ? 5 : 1} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} /> ); } }
Source: https://habr.com/ru/post/276585/
All Articles