React.js-在画布上绘制图像时缩放图像

时间:2020-01-09 11:48:40

标签: javascript html reactjs

我正在尝试将图像绘制到画布上,图像源是用户选择的图像文件。用户选择图像后,他们单击按钮以将其绘制到页面上的画布上(600px x 600px)。我已经做过一些研究,但是我想不出一种好方法来防止将图像绘制到画布上时图像被拉伸/挤压。

这是沙箱:

https://codesandbox.io/s/sweet-http-ti0zi

这是代码:

constructor(props) {
    super(props);
    this.state = {
      image: ""
    };
  }

  renderCanvas() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var img = document.getElementById("user-Img");

    // calculate the scaling factor to resize new image to
    //     fit MAX dimensions without overflow
    var scalingFactor = Math.min(600 / img.width, 600 / img.height);

    // calc the resized img dimensions
    var iw = img.width * scalingFactor;
    var ih = img.height * scalingFactor;

    // resize the canvas to the new dimensions
    canvas.width = iw;
    canvas.height = ih;

    // scale & draw the image onto the canvas
    ctx.drawImage(img, 0, 0, iw, ih);
  }

  onImageChange = async event => {
    if (event.target.files && event.target.files[0]) {
      await this.setState({
        image: URL.createObjectURL(event.target.files[0])
      });
      //Load image into div
      var imagePreview = (
        <div>
          <div id="circularEdit">
            <img
              id="target"
              src={this.state.image}
              className="center"
              style={{ verticalAlign: "middle", cursor: "pointer" }}
              id="user-Img"
            />
          </div>
        </div>
      );
      ReactDOM.render(imagePreview, document.getElementById("picturePreview"));
    }
  };
  render() {
     return (
      <div>
        <input
          type="file"
          id="profile-picture-file"
          onChange={this.onImageChange}
          name="myImage"
          accept="image/*"
          ref={ref => (this.fileUpload = ref)}
        />
        <h5>Image Preview</h5>
        <div id="picturePreview" />
        <button onClick={() => this.renderCanvas()}>Map to canvas</button>
        <canvas
          id="myCanvas"
          width="600"
          height="600"
          style={{ objectFit: "cover" }}
        />
      </div>
    );
  }

“ circularEdit” div ID上有一些CSS,如下所示:

#circularEdit img {
  object-fit: cover;
  border-radius: 5px;
  width: 150px;
  height: 150px;
}

这将切除不适合div的图像任何部分,而不会牺牲图像的纵横比。是否可以将相同的逻辑应用于画布?

0 个答案:

没有答案
相关问题