Fabric js 图像过滤器未正确应用

Fabric js images filters not applied properly

提问人:Tyler Rake 提问时间:11/13/2023 最后编辑:Tyler Rake 更新时间:11/14/2023 访问量:20

问:

因此,当我对我选择的图像应用滤镜时,会出现第二张图像(原始颜色),但是当我再次单击该图像时,它消失了

这是完整的代码,我添加了一个图像来显示问题

function App(props) {
  const [selectedObject, setSelectedObject] = useState(null);
  const [hueRotation, setHueRotation] = useState(0);
  const canvasRef = useRef(null);
  const modifiedObjectsRef = useRef({});


    useEffect(() => {
        const canvas = new fabric.Canvas('productCanvas', {
            backgroundColor: 'transparent',
        });
        canvasRef.current = canvas;

        const { frontView, backView, sideView, additionalImages } = props.selectedImages;

        const images = [frontView, backView, sideView, ...additionalImages];

        const separation = 5; // Adjust the separation between images as needed
        let leftPosition = 0;

        // Load images onto the canvas with separation
        images.forEach((image, index) => {
            const imageUrlPromise = convertImageToFileURL(image);

            imageUrlPromise.then((imageUrl) => {
                fabric.Image.fromURL(imageUrl, (productImage) => {
                    productImage.scaleToWidth(100);
                    productImage.set({
                        selectable: true,
                        evented: true,
                        top: 10,
                        left: 10,
                    });
                    leftPosition += productImage.width + separation;
                    canvas.add(productImage);
                });
            }).catch((error) => {
                console.error('Error converting image to URL:', error);
            });
        });

        // Event listener for when an object (image) is selected
        canvas.on('mouse:up', (event) => {
            const target = event.target;
            if (target && target.type === 'image') {
              console.log('Image clicked:', target);
              setSelectedObject(target);

              const hueFilter = new fabric.Image.filters.HueRotation({
                rotation: 350, // Adjust the rotation angle as needed
              });
          
              // Apply the hue filter to the target image
              target.filters.push(hueFilter);
              target.applyFilters();
              canvas.renderAll();
              }
        });
        canvas.setDimensions({
            width: window.innerWidth,
            height: window.innerHeight * 0.75,
        });
    }, []);


    const handleSliderChange = (event) => {
      const value = parseInt(event.target.value, 10);
      setHueRotation(value);
    
      if (selectedObject) {
        // Clone the selected object
        const clonedObject = fabric.util.object.clone(selectedObject);
    
        // Get the canvas element
        const canvasElement = canvasRef.current.lowerCanvasEl;
    
        // Create a 2D rendering context
        const ctx = canvasElement.getContext('2d');
    
        // Draw the image on an off-screen canvas to manipulate pixel data
        const offScreenCanvas = document.createElement('canvas');
        const offScreenCtx = offScreenCanvas.getContext('2d');
        offScreenCanvas.width = clonedObject.width;
        offScreenCanvas.height = clonedObject.height;
        offScreenCtx.drawImage(clonedObject._element, 0, 0, clonedObject.width, clonedObject.height);
    
        // Get the image data from the off-screen canvas
        const imageData = offScreenCtx.getImageData(0, 0, clonedObject.width, clonedObject.height);
        const data = imageData.data;
    
        // Adjust the hue
        for (let i = 0; i < data.length; i += 4) {
          const rgb = [data[i], data[i + 1], data[i + 2]];
          const hsl = rgbToHsl(rgb);
          hsl[0] = (hsl[0] + value) % 360;
          const newRgb = hslToRgb(hsl);
          data[i] = newRgb[0];
          data[i + 1] = newRgb[1];
          data[i + 2] = newRgb[2];
        }
    
        // Put the modified image data back on the off-screen canvas
        offScreenCtx.putImageData(imageData, 0, 0);
    
        // Update the cloned object with the modified image
        clonedObject.setElement(offScreenCanvas);
    
        // Replace the original object with the cloned object on the canvas
        canvasRef.current.remove(selectedObject);
        canvasRef.current.add(clonedObject);
        canvasRef.current.setActiveObject(clonedObject);
        canvasRef.current.requestRenderAll();
      }
    };
    
    // Helper function to convert RGB to HSL
    function rgbToHsl(rgb) {
    }
    
    // Helper function to convert HSL to RGB
    function hslToRgb(hsl) {
    }
    
    function convertImageToFileURL(imageFile) {
    }

    return (
      <div>
        <section>
            <canvas id="productCanvas" />
        </section>
        <div style={{marginTop: '20px'}}>
        <label htmlFor="rotationSlider">Hue Rotation:</label>
                <input
                    type="range"
                    id="rotationSlider"
                    min="0"
                    max="360"
                    step="1"
                    value={hueRotation}
                    onChange={handleSliderChange}
                />
                <span>{hueRotation} degrees</span>
            </div>
      </div>
    );
}

export default App;

使用滑块时的图像,在此处输入图像描述

这就是我点击图像后发生的情况 它重置为我设置的色调,一切看起来都很正常,在此处输入图像描述

如果可以的话,请给出一个在 React 中将过滤器应用于多个图像的代码示例

javascript reactjs canvas fabricjs

评论

1赞 Community 11/13/2023
请修剪您的代码,以便更轻松地找到您的问题。请遵循这些准则,以创建最小的可重现示例
1赞 isherwood 11/13/2023
请参阅“如何提问”并参观,然后修改您的帖子标题以提出清晰、具体的问题。不要添加标签。

答: 暂无答案