简体   繁体   中英

Drawing a canvas in react

I am still new to react and JavaScript and I want to implement a function to draw a series of shapes. Eg a series of circles, rectangles or triangles. Recently, I have found a project on GitHub named "react designer" in the following link: Link Here and here is how drawing a circle is done:

export default class Circle extends Vector {
 static meta = {
icon: <Icon icon={"circle"} size={30} />,
initial: {
  width: 5,
  height: 5,
  rotate: 0,
  // fill: "yellow",
  strokeWidth: 0,
  blendMode: "normal"
}
};

render() {
let { object, index } = this.props;
return (
  <ellipse
    fill={this.state.isClicked ? "green" : "red"}
    style={this.getStyle()}
    {...this.getObjectAttributes()}
    onClick={() => {
      this.setState({ isClicked: true });
    }}
    rx={object.width / 2}
    ry={object.height / 2}
    cx={object.x + object.width / 2}
    cy={object.y + object.height / 2}
  />
);

What I want to ask is, is there a way to draw multiple circles instead of one using the same component? Or is there a whole different way to do so. Thanks in advance.

For example if you want to do the same twice in the same component, you can create a wrapper around the <ellipse> component and put them twice.

Please refer a possible working solution:

return <>
  <ellipse {/* your attributes */}/>
  <ellipse {/* your attributes */}/>
</>

Additionally you need to change the <ellipse> component's cx attribute to have different values for each circles because that's the way not to render them on the same coordinates. Once you have different values you will see them in separate locations, if you leave the value for both exact the same then it will render them as well but their will be overlapping each other.

This wrapper is called React Fragment, read further here: https://reactjs.org/docs/fragments.html

Or you can create an array which stores the state of each circles where you can use Array.prototype.map() to render each.

For example like this:

return <>
  {circles.map(e => <ellipse {/* your attributes */}/>}
</>

I hope that helps! Let me know if further explanation is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM