In react, canvas is used to draw various charts, animations, etc.; you can use canvas using the "react-konva" plug-in, which is a canvas third-party library used to use React to operate canvas to draw complex Canvas graphics, and provides event mechanism for elements and support for drag-and-drop operations.
The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.
Canvas is a new component of HTML5. It is like a curtain on which various charts, animations, etc. can be drawn using JavaScript.
It is a characteristic of Canvas that it can only be driven by js scripts.
canvas element
<canvas id='mycanvas' width=400 height=400> Your browser does not support the canvas element. </canvas>
Browsers that support canvas will only render the canvas tag and ignore the alternative content. Browsers that do not support canvas will render alternative content directly.
Explain that other DOM structures cannot be nested inside the canvas.
react-konva
Let’s learn about the application of canvas in react. We will use the react-konva plugin.
react-konva and react-canvas are react-related canvas third-party libraries with more stars on github. Since react-canvas has not been updated since March 2017 and does not support react 16, it will no longer be considered. Here we mainly introduce the use of react-konva.
React Konva is a JavaScript library for drawing complex canvas graphics using React. It allows us to operate the canvas just like operating the DOM, and provides support for the event mechanism and drag-and-drop operations of elements in the canvas.
Basic concept
Consider the entire view as a stage. Each layer in the stage is regarded as a layer. There are many groups in the layer layer. Draw shapes such as drawings and pictures in the group.
Examples are as follows;
import React, { Component } from "react"; import Konva from "konva"; import { render } from "react-dom"; import { Stage, Layer, Rect, Text } from "react-konva"; class ColoredRect extends React.Component { state = { color: "green" }; handleClick = () => { this.setState({ color: Konva.Util.getRandomColor() }); }; render() { return ( <Rect x={20} y={20} width={50} height={50} fill={this.state.color} shadowBlur={5} onClick={this.handleClick} /> ); } } class App extends Component { render() { return ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> <Text text="Try click on rect" /> <ColoredRect /> </Layer> </Stage> ); } }
Recommended learning: "react video tutorial"
The above is the detailed content of What is the usage of canvas in react. For more information, please follow other related articles on the PHP Chinese website!