JSFiddle - React, Tailwind, and code Playground

by DupontTD

HTML

<canvas height="300" width="500" class="canvas" />
<p>Dessine moi un mouton !</p>

JavaScript

class Point {
  constructor(x, y) {
    Object.assign(this, {
      x,
      y
    })
  }

  static construct(x = Math.round(500 * Math.random()),
                   y = Math.round(300 * Math.random())) {
    return new Point(x, y);
  }
}


class Shape {

  constructor(tabPoints) {
    this.points = tabPoints;
    this.lines = [];

    Shape.init();
  }

  static construct(...points) {
    return new Shape(points);
  }

  static init() {
    console.log("Appel la méthode Static init");
    if (typeof Shape.context === 'undefined') {
      let canvas = document.querySelector('.canvas');
      Shape.context = canvas.getContext('2d');
    }
  }
  // method that draws a shape by looping through this.points
  draw() {
    let ctx = Shape.context;
    ctx.fillStyle = this.getColor();
    ctx.beginPath();

    this.points.forEach(({
      x,
      y
    }, i) => {
      console.log(x, y);
      if (i == 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);

      }

    });
    ctx.closePath();
    ctx.fill();

    return this;

  }

  // method that generates a random color
  getColor() {

    let rgb = Array.from({
      length: 3
    }, () => Math.round(255 * Math.random()));
    rgb[3] = Math.random() + 0.05; // à->1
    return `rgba(${rgb.join(',')})`;
  }
}



class Triangle extends Shape {

  constructor( [P1,P2,P3] ) {
    super( [P1,P2,P3] );
  }
  
  static construct(...points) {
      try {
            if (points.length>3) {
                console.log("Un triangle à trois points -> tonque ");
            }
            return new Triangle(points);
        }
        catch (e) {
            console.log(e);
        }  
  }
  
  // calcul surface

}

  Triangle.construct(Point.construct(),Point.construct(0,0), Point.construct(0,100), Point.construct(300)).draw();
  

class Rectangle extends Shape{

 constructor([P1,P2,P3,P4]) {
    super( [P1,P2,P3,P4] );
  }
  
  static construct( {x,y}, side_a, side_b) {
    let points = [
        {x,y},
     ...