如何使用 canvas 和 useRefs 在 React 中显示二进制图像
How to display binary image in react using canvas and useRefs
我有一个 [255, 0, 0, 255] 形式的模拟 RGBA 图像,我想使用 React 在我的网页上显示它。
mockImageArray = [255, 0, 0, 255];
var mockImage = new ImageData(new Uint8ClampedArray(mockImageArray), 1, 1);
const Canvas = (props) => {
const canvasRef = useRef(null);
const draw = (ctx) => {
var imageData = ctx.createImageData(mockImage);
ctx.putImageData(imageData, 0, 0);
};
useEffect(() => {
const canvas = canvasRef.current;
canvas.width = 512;
canvas.height = 256;
const context = canvas.getContext("2d");
draw(context);
}, [draw]);
return <canvas ref={canvasRef} {...props} />;
};
当我在主组件中加载此组件时,我期待一个红色像素,但是,我似乎无法加载任何东西。元素甚至不会出现在元素选项卡中。有人可以指导我哪里出错了吗?
谢谢!
根据 MDN,createImageData
doesn't copy the image data from the buffer。
imagedata
An existing ImageData object from which to copy the width and height. The image itself is not copied.
无论如何您都不需要创建单独的 imageData
;
ctx.putImageData(mockImage, 20, 20);
工作得很好(移动到 20,20 因为它更容易看到)。
我有一个 [255, 0, 0, 255] 形式的模拟 RGBA 图像,我想使用 React 在我的网页上显示它。
mockImageArray = [255, 0, 0, 255];
var mockImage = new ImageData(new Uint8ClampedArray(mockImageArray), 1, 1);
const Canvas = (props) => {
const canvasRef = useRef(null);
const draw = (ctx) => {
var imageData = ctx.createImageData(mockImage);
ctx.putImageData(imageData, 0, 0);
};
useEffect(() => {
const canvas = canvasRef.current;
canvas.width = 512;
canvas.height = 256;
const context = canvas.getContext("2d");
draw(context);
}, [draw]);
return <canvas ref={canvasRef} {...props} />;
};
当我在主组件中加载此组件时,我期待一个红色像素,但是,我似乎无法加载任何东西。元素甚至不会出现在元素选项卡中。有人可以指导我哪里出错了吗? 谢谢!
根据 MDN,createImageData
doesn't copy the image data from the buffer。
imagedata
An existing ImageData object from which to copy the width and height. The image itself is not copied.
无论如何您都不需要创建单独的 imageData
;
ctx.putImageData(mockImage, 20, 20);
工作得很好(移动到 20,20 因为它更容易看到)。