Day 23/100 React Fabric. JS to realize the line shape that can be dragged and rotated

Time:2022-1-2

1. Demand

Draw a line between two points on the canvas and mark it on the canvas.

2. Realize

var line = new fabric.Line([10, 20, 115, 110], {
    strokeWidth: 2,
    stroke: 'red',
    originX: 'center',
    originY: 'center'
});
canvas.add(line);

The effects are as follows:
Day 23/100  React Fabric. JS to realize the line shape that can be dragged and rotated

3. Complete code

/*
 * @Author: ArdenZhao
 * @Date: 2021-12-07 11:35:45
 * @LastEditors: Do not edit
 * @LastEditTime: 2021-12-30 14:29:52
 * @FilePath: /react-ts/src/components/Fabric.js
 */
import React from 'react';
import { fabric } from "fabric";
class Fabric extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            canvas:new fabric.Canvas('canvas')
        }
    }
    componentDidMount(){
        fabric. textureSize = 5120;// Limit the upper limit of picture to 5M 1024 * 5 = 5120
        const canvas = new fabric.Canvas('canvas');
        console.log('canvas',canvas);
        //// picture
        const imgEl = document.createElement('img')
        imgEl. Crossorigin = 'anonymous' // make the picture accessible to everyone
        imgEl.src = 'https://2.bp.blogspot.com/-H3JXh2cIKHs/WuwLvnz19cI/AAAAAAAAMXs/-qySdr5zEcc-kcLC4arf5m5H3F_trN7sgCK4BGAYYCw/s1600/kristopher-roller-110203-unsplash-m.jpg'
        imgEl.onload = () => {
            const image = new fabric.Image(imgEl, {
                scaleX: 0.5,
                scaleY: 0.5,
                angle: 0,
                // angle: 15,
                top: 0,
                left: 0
            })
            //Push the filters instance into the filters
            image.filters.push(new fabric.Image.filters.Contrast({contrast: 0.2}))
            //All filter effects need to be reorganized here
            image.applyFilters()
            canvas.add(image)
            var line = new fabric.Line([10, 20, 115, 110], {
                strokeWidth: 2,
                stroke: 'red',
                originX: 'center',
                originY: 'center'
            });
            canvas.add(line);
        }
    };
    render() {
        return <div>
            <h1>Learn, {this.props.name}</h1>
            <canvas id="canvas" width="666" height="600"></canvas>
        </div>;
    }
}
export default Fabric;
GitHub address

https://github.com/iguoxing/r…

Reference link

1. Official API
http://fabricjs.com/docs/fabr…

2. Demo document
https://www.coder.work/articl…

3. Online demo
http://jsfiddle.net/ydtt94zm/