Reputation: 1
I am working on a project in React JS uisng of Three.js and need to implement a functionality where users can upload an image via drag-and-drop. If the image intersects with the canvas, the overlapping portion of the image should be applied as a texture to a child of a box model. How can I achieve this functionality?
Here is my code when i am dragg stop at that point it will check image is inside of the canvas or not if yes then it will provide the value or return the array as intersect part. am I going in right direction ?
const handleDragStop = (e, data) => {
const canvasRect = canvasRef.current.getBoundingClientRect();
const imageCenterX = data.x + data.node.clientWidth / 2;
const imageCenterY = data.y + data.node.clientHeight / 2;
console.log('Canvas Rect:', canvasRect);
console.log('Image Center:', imageCenterX, imageCenterY);
// Ensure the image is within the bounds of the canvas
if (
imageCenterX >= canvasRect.left &&
imageCenterX <= canvasRect.right &&
imageCenterY >= canvasRect.top &&
imageCenterY <= canvasRect.bottom
) {
const canvasX = (imageCenterX - canvasRect.left) / canvasRect.width * 2 - 1;
const canvasY = -(imageCenterY - canvasRect.top) / canvasRect.height * 2 + 1;
console.log('NDC:', canvasX, canvasY);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(new THREE.Vector2(canvasX, canvasY), boxCamera.current);
const intersects = raycaster.intersectObjects(boxScene.current.children, true);
console.log('Intersects:', intersects);
if (intersects.length > 0) {
const intersectedMesh = intersects[0].object;
// Apply the image as a texture to the intersected mesh
const textureLoader = new THREE.TextureLoader();
textureLoader.load(imgSrc, (texture) => {
intersectedMesh.material.map = texture;
intersectedMesh.material.needsUpdate = true;
});
// Reset the position of the draggable image
setDragPosition({ x: 0, y: 0 });
}
} else {
console.log('Image is outside the bounds of the canvas');
}
};
Upvotes: 0
Views: 26