Garmaine Staff asked 2 years ago

I am creating a project where I take an svg path and turn it into an array of coordinates so that I can use them for my Fourier Transform function later. I'm saying to the user to upload an SVG file (locally), then I add the SVG to the DOM, then I try to select the path tag to extract the coordinates, but the selection returns null ! I am using ReactJS and other APIs.

I also have other questions :

1 – Is it better to leave all the SVG manipulation client sided, or I should make it server side ?

2- Is there a better API that can allow me extract the path or coordinates from the SVG file ?

Thanks, and stay safe.

import { ReactSVG } from 'react-svg';
import Sketch from '../sketch/Sketch';
import './ImageUploader.scss';


class ImageUploader extends Component {
  constructor( props ) {
    super( props );
    this.state = {
      pointsArray : [],
      fileURL : null,
      file: null
    }
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange = (event) => {
    this.setState({
      file : event.target.files[0],
      fileURL: URL.createObjectURL(event.target.files[0])
    })

  }

  add_svg = () => {
    console.log(this.state.file);
    if (this.state.fileURL !== null) {
      return <ReactSVG src={this.state.file.name} />;
    }
    return null;
  }

  render() {

    if (this.state.fileURL !== null) {
      const path = document.querySelector('path');
      console.log(path);
      // const length = path.getTotalLength();
      // const step = length / 100;
      // for (let i = length - 1; i >= 0; i -= step) {
      //     console.log(path.getPointAtLength(i));
      // }
    }
    return (

      <div >

        <div className="upload_sketch_container">

          <div className="input_container">
            <input type="file" id="file" onChange={this.handleChange} />
            <label htmlFor="file">Upload SVG file</label>
          </div>

          <div className="image_sketch_container">

            <div className="image_container" >
              {this.add_svg()}
            </div>

            <div className="sketch_container">
              <Sketch data={this.state.pointsArray} />
            </div>

          </div>
        </div>

      </div>
    );
  }
}

export default ImageUploader;