рисование 4 кружков на холсте в реактив - PullRequest
0 голосов
/ 15 октября 2019

Я пытаюсь нарисовать многоцветные круги на холсте. Когда я рисую один круг, предыдущий круг был удален. Поэтому я создал функцию для копирования предыдущего круга, но там я не смог получить точную координату центра круга, и была создана прямая линия. Я делюсь своим кодом. В функции рисования круга мне нужны правильные centerx и centery.


class Circle extends Component {
    constructor(props) {
        super(props);
        //added state 
        this.state = {
            isDown: false,
            previousPointX: '',
            previousPointY: '',
            base_image: {},
            circleConfig: {
                maxCircle: 4,
                color: ["red", "blue", "#ffa500", "green"]
            },
            circles: [],
            canvasId: this.props.canvasid,
            rotate:this.props.rotate
        }
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.handleMouseMove = this.handleMouseMove.bind(this);
        this.handleMouseUp = this.handleMouseUp.bind(this);
    }

    render() {
        return (
            
                 {
                            let nativeEvent = e.nativeEvent;
                            this.handleMouseDown(nativeEvent);
                        }}
                    onMouseMove={
                        e => {
                            let nativeEvent = e.nativeEvent;
                            this.handleMouseMove(nativeEvent);
                        }}
                    onMouseUp={
                        e => {
                            let nativeEvent = e.nativeEvent;
                            this.handleMouseUp(nativeEvent);
                        }}
                />
                {JSON.stringify(this.state.lines, null, 2)}
);} drawCircle (circle, ctx) {console.log ('draw circle', circle) circle.forEach ((item) => {var r = (item.endx-item.startx) / 2; var centerx = (item. endx-item.startx) / 2; var centery = (item.endy-item.starty) / 2; ctx.arc (centerx, centery, r, 0, 2 * Math.PI); ctx.strokeStyle = item.color;})} handleMouseDown (event) {if (this.state.circles.length> = this.state.circleConfig.maxCircle) return;this.setState ({isDown: true, previousPointX: event.offsetX, previousPointY: event.offsetY}, () => {console.log ('mousedown', this.state)})} handleMouseMove (event) {if (this.state.isDown) {event.preventDefault ();event.stopPropagation ();const canvas = ReactDOM.findDOMNode (this.refs.canvas);var x = event.offsetX;var y = event.offsetY;var ctx = canvas.getContext ("2d");ctx.clearRect (0, 0, canvas.width, canvas.height);ctx.drawImage (this.state.base_image, 0, 0);// Сохранить ctx.save ();ctx.beginPath ();this.drawCircle (this.state.circles, СТХ);var circleLength = this.state.circles.length ||0;// Динамическое масштабирование var scalex = (x-this.state.previousPointX) / 2;var scaley = (y-this.state.previousPointY) / 2;ctx.scale (Scalex, ScaleY);// Создать эллипс var centerx = (this.state.previousPointX / scalex) +1;var centery = (this.state.previousPointY / scaley) +1;ctx.arc (centerx, centery, 1, 0, 2 * Math.PI);ctx.restore ();ctx.stroke ();ctx.strokeStyle = this.state.circleConfig.color [circleLength] ;;}} handleMouseUp (event) {if (this.state.circles.length> = this.state.circleConfig.maxCircle) return;this.setState ({isDown: false});console.log ('mouseup', this.state) const canvas = ReactDOM.findDOMNode (this.refs.canvas);var x = event.offsetX;var y = event.offsetY;var ctx = canvas.getContext ("2d");var circleLength = this.state.circles.length ||0;if (this.state.previousPointX! == x && this.state.previousPointY! == y) {this.setState ({circle: this.state.circles.concat ({startx: this.state.previousPointX, starty: this.state.previousPointY, endx: x, endy: y, цвет: this.state.circleConfig.color [circleLength]})}, () => {ctx.stroke (); ctx.closePath (); this.props. drawCircleToStore (this.state.circles, this.state.canvasId, this.props.imgSrc, this.state.rotate)});}} componentDidMount () {const canvas = ReactDOM.findDOMNode (this.refs.canvas);const ctx = canvas.getContext ("2d");const base_image = new Image ();base_image.src = this.props.imgSrc base_image.onload = function () {ctx.drawImage (base_image, 0, 0);} this.setState ({base_image: base_image});}}

1 Ответ

0 голосов
/ 18 октября 2019

В методе drawCircle координата центра будет

var r = (item.endx - item.startx) / 2;
centerx = (r + item.startx);
centery = (r + item.starty);
ctx.arc(centerx, centery, r, 0, 2 * Math.PI);





class CircleMultiple extends Component {
    constructor(props) {
        super(props);
        //added state 
        this.state = {
            isDown: false,
            previousPointX: '',
            previousPointY: '',
            base_image: {},
            circleConfig: {
                maxCircle: 4,
            },
            circles: [],
            canvasId: this.props.canvasid,
            rotate: this.props.rotate
        }
        this.handleMouseDown = this.handleMouseDown.bind(this);
        this.handleMouseMove = this.handleMouseMove.bind(this);
        this.handleMouseUp = this.handleMouseUp.bind(this);
    }

    render() {
        return (
            
                 {
                            let nativeEvent = e.nativeEvent;
                            this.handleMouseDown(nativeEvent);
                        }}
                    onMouseMove={
                        e => {
                            let nativeEvent = e.nativeEvent;
                            this.handleMouseMove(nativeEvent);
                        }}
                    onMouseUp={
                        e => {
                            let nativeEvent = e.nativeEvent;
                            this.handleMouseUp(nativeEvent);
                        }}
                />
                {JSON.stringify(this.state.circles, null, 2)}
);} drawCircle (circle, ctx) {circle.forEach ((item) => {ctx.beginPath (); var r = (item.endx - item.startx) / 2; var centerx = (r + item.startx);var centery = (r + item.starty); ctx.arc (centerx, centery, r, 0, 2 * Math.PI); ctx.stroke (); ctx.closePath ();})} handleMouseDown (event) {if (this.state.circles.length> = this.state.circleConfig.maxCircle) return;this.setState ({isDown: true, previousPointX: event.offsetX, previousPointY: event.offsetY}, () => {// console.log ('mousedown', this.state)})} handleMouseMove (event) {if(this.state.isDown) {event.preventDefault ();event.stopPropagation ();const canvas = ReactDOM.findDOMNode (this.refs.canvas);var x = event.offsetX;var y = event.offsetY;var ctx = canvas.getContext ("2d");ctx.clearRect (0, 0, canvas.width, canvas.height);// ctx.drawImage (this.state.base_image, 0, 0);ctx.drawImage (this.state.base_image, canvas.width / 2 - this.state.base_image.width / 2, canvas.height / 2 - this.state.base_image.height / 2);// Сохранить ctx.save ();ctx.beginPath ();this.drawCircle (this.state.circles, ctx);// var circleLength = this.state.circles.length ||0;// Динамическое масштабирование var scalex = (x - this.state.previousPointX) / 2;var scaley = (y - this.state.previousPointY) / 2;ctx.scale (scalex, scaley);// Создать эллипс var centerx = (this.state.previousPointX / scalex) + 1;var centery = (this.state.previousPointY / scaley) + 1;ctx.beginPath ();ctx.arc (centerx, centery, 1, 0, 2 * Math.PI);ctx.restore ();ctx.stroke ();// ctx.strokeStyle = this.state.circleConfig.color [circleLength];// console.log ('centerx', centerx, 'centery', centery)}} handleMouseUp (event) {if (this.state.circles.length> = this.state.circleConfig.maxCircle) return;this.setState ({isDown: false});// console.log ('mouseup', this.state) var x = event.offsetX;var y = event.offsetY;if (this.state.previousPointX! == x && this.state.previousPointY! == y) {this.setState ({circle: this.state.circles.concat ({startx: this.state.previousPointX, starty: this.state.previousPointY, endx: x, endy: y, r: (x - this.state.previousPointX) / 2, centerx: ((((x - this.state.previousPointX) / 2) + this.state.previousPointX), centery: (((x - this.state.previousPointX) / 2) + this.state.previousPointY) // color: this.state.circleConfig.color [circleLength]})}, () => {// console.log ('mouseup', this.state);});}} componentDidMount () {const canvas = ReactDOM.findDOMNode (this.refs.canvas);const ctx = canvas.getContext ("2d");const base_image = new Image ();base_image.src = this.props.imgSrc base_image.onload = function () {// ctx.drawImage (base_image, 0, 0);ctx.drawImage (base_image, canvas.width / 2 - base_image.width / 2,canvas.height / 2 - base_image.height / 2);} this.setState ({base_image: base_image});}} экспорт по умолчанию CircleMultiple;

Для удаления соединительной линии между кругами необходимо добавить

            ctx.beginPath();

перед вызовом метода drawCircle ().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...