反应-使用画布从图像中删除空白不起作用

时间:2019-05-17 10:13:21

标签: reactjs canvas

我正在尝试从图像中删除空白,我试图使用画布来删除空白,但是它不起作用。我已经成功地将图像加载到画布上,然后在尝试删除空白页面之后却无法正常工作,甚至图像也没有放在画布上。

我指的是下面的例子:

Remove white space using JQuery
React function to remove whitespace

我做了一些代码,并创建了Component来删除Image中的空白,但是它不起作用。

这是我的代码。

import React, { Component } from 'react';

class Canvas extends Component {
  componentDidMount() {
    const canvas = document.querySelector("canvas");
    const context = canvas.getContext("2d");

    const img = new Image();

    img.onload = function () {
      context.drawImage(this, 0, 0); // put the image in the canvas
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;

      const getAlpha = function(x, y) {
        return data[(imgWidth*y + x) * 4 + 3]
      };
      const scanY = function (fromTop) {
        const offset = fromTop ? 1 : -1;

        // loop through each row
        for(let y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {

          // loop through each column
          for(let x = 0; x < imgWidth; x++) {
            if (getAlpha(x, y)) {
              return y;
            }
          }
        }
        return null; // all image is white
      };
      const scanX = function (fromLeft) {
        const offset = fromLeft? 1 : -1;

        // loop through each column
        for(let x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {

          // loop through each row
          for(let y = 0; y < imgHeight; y++) {
            if (getAlpha(x, y)) {
              return x;
            }
          }
        }
        return null; // all image is white
      };

      const cropTop = scanY(true);
      const cropBottom = scanY(false);
      const cropLeft = scanX(true);
      const cropRight = scanX(false);

      const relevantData =
        context.getImageData(cropLeft, cropTop, cropRight-cropLeft, cropBottom-cropTop);
      canvas.width = cropRight-cropLeft;
      canvas.height = cropBottom-cropTop;
      context.clearRect(0, 0, cropRight-cropLeft, cropBottom-cropTop);
      context.putImageData(relevantData, 0, 0);


    };

    img.crossOrigin="anonymous";
    img.src = 'https://images-na.ssl-images-amazon.com/images/I/41-B7sd9tgL.jpg';

  }

  render() {

    return(
      <div>
        <canvas />
      </div>
    );

  };

}

export default Canvas

有人可以帮忙吗? 预先感谢

0 个答案:

没有答案