Поверните изображение внутри холста и загрузите повернутое изображение - PullRequest
0 голосов
/ 28 января 2019

Я пытаюсь повернуть изображение и сохранить его после этого.Моя проблема не в повороте, но когда я сохраняю изображение, изображение не имеет поворота.

Код:

rotate = (value) => {
     //get canvas context
    const ctx = this.canvasRef.getContext("2d");
    var img = new Image();
    img.src = this.state.imgsource;
    var cw = img.width, ch = img.height, cx = 0, cy = 0;
    value = this.state.cont + value;
    //   Calculate new canvas size and x/y coorditates for image

    //rotation Code here

 //setting state of rotation
    if (this.state.cont == 270 || this.state.cont == -270) {
        this.setState({ cont: 0 });
    } else {
        this.setState({ cont: value });
    }
      //draw the image with the rotation
    this.canvasRef.setAttribute('width', cw);
    this.canvasRef.setAttribute('height', ch);
    ctx.rotate(value * Math.PI / 180);
    img.onload = function () {
        ctx.drawImage(img, cx, cy);
    };
    ctx.save();
  //getting the last state of the image 
    this.setState({ imgsource: img.src });

}

1 Ответ

0 голосов
/ 28 января 2019

Загрузка изображения - это асинхронное действие, поэтому вам нужно будет сохранить контекст после загрузки изображения.затем обновите состояние.

rotate = (value) => {
     //get canvas context
    const ctx = this.canvasRef.getContext("2d");
    var img = new Image();
    img.src = this.state.imgsource;
    var cw = img.width, ch = img.height, cx = 0, cy = 0;
    value = this.state.cont + value;
    //   Calculate new canvas size and x/y coorditates for image

    //rotation Code here

 //setting state of rotation
    if (this.state.cont == 270 || this.state.cont == -270) {
        this.setState({ cont: 0 });
    } else {
        this.setState({ cont: value });
    }
      //draw the image with the rotation
    this.canvasRef.setAttribute('width', cw);
    this.canvasRef.setAttribute('height', ch);
    img.onload = function () {
        ctx.drawImage(img, cx, cy);
        ctx.rotate(value * Math.PI / 180);
        ctx.save();
        this.setState({ imgsource: img.src });
    };
  //getting the last state of the image 

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