Я пытаюсь удалить пробел из Image, я пытался удалить пробел, используя canvas, но он не работает. Я успешно загрузил изображение на холст, а затем попытался удалить пустую страницу, но он не работает, даже изображение не помещается на холст.
Я имею в виду приведенные ниже примеры:
Удаление пробелов с помощью JQuery
Реактивная функция для удаления пробелов
Я сделал некоторый код и создал Компонент, чтобы удалить пробел из 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
Кто-нибудь может помочь?
Заранее спасибо