在画布内旋转图像并下载旋转后的图像

时间:2019-01-28 18:37:58

标签: javascript html reactjs canvas

我正在尝试旋转图像并保存。 我的问题不是旋转,但是当我保存图像时,图像没有旋转。

代码是:

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 :(得分:0)

图像加载是异步操作,因此在图像加载后必须保存上下文。然后更新状态。

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 

}