图片未正确旋转

huangapple go评论99阅读模式
英文:

Image is not rotating properly

问题

function Design() {

    const [isHovered_t, setIsHovered_t] = useState(false);
    const [isHovered_i, setIsHovered_i] = useState(false);
    const [isHovered_c, setIsHovered_c] = useState(false);

    const [isHovered_tg, setIsHovered_tg] = useState(false);
    const [isHovered_ig, setIsHovered_ig] = useState(false);
    const [isHovered_cg, setIsHovered_cg] = useState(false);

    const [fontSize, setFontSize] = useState(10);
    const [outlineWidth, setOutlineWidth] = useState(0);
    const [rotate, setRotate] = useState(0);

    const [soleColor, setSoleColor] = useState(right_w);
    const [shoeSide, setShoeSide] = useState("right");

    const [imageSize, setImageSize] = useState({ x: 100, y: 100 });
    const [imageSizes, setImageSizes] = useState([]);

    const [images, setImages] = useState([]);
    const [imagePositions, setImagePositions] = useState([]);

    var targetImage;
    const [strapColor, setStrapColor] = useState("black");

    const [rotationAngle, setRotationAngle] = useState(0);
    const [isRotating, setIsRotating] = useState(false);
    const [initialAngle, setInitialAngle] = useState(0);

    var resize_v_s = false;

    const canvasRef = useRef(null);
    var animationFrame;

    const quick_draw = () => {
        // ... (code for quick_draw)
    }

    const draw_image = () => {
        // ... (code for draw_image)
    }

    const stopDrawingImages = () => {
        // ... (code for stopDrawingImages)
    };

    const imageCache = {};
    const preloadImages = () => {
        // ... (code for preloadImages)
    };

    useEffect(() => {
        // ... (code for useEffect)
    }, [images, imagePositions, strapColor, imageSizes])

    const handleOnMouse = (e) => {
        // ... (code for handleOnMouse)
    }

    const handleMouseDown = (e) => {
        // ... (code for handleMouseDown)
    }

    const handleRotate = (e) => {
        // ... (code for handleRotate)
    }

    const handleResize = (e) => {
        // ... (code for handleResize)
    }

    const handleResizeZ = (e) => {
        // ... (code for handleResizeZ)
    }

    const handleMouseMove = (e) => {
        // ... (code for handleMouseMove)
    };

    const handleMouseUp = () => {
        // ... (code for handleMouseUp)
    };
    
    const handleImageUpload = (event) => {
        // ... (code for handleImageUpload)
    };
   
   return (
        <>
            <Navbar />
            <div id="designContainer">

                <div id="canvasContainer">
                    <img src={soleColor} alt="black slippers" />
                    <canvas onMouseMove={handleOnMouse} onMouseDown={handleMouseDown} ref={canvasRef} id="canvas">
                        <p>Hello, I am canvas</p>
                    </canvas>
                </div>
        </>
    );
}

export default Design;
英文:
import rotate_i from &quot;../assets/rotate.png&quot;;
import resize_1 from &quot;../assets/resize_1.png&quot;;
import resize_2 from &quot;../assets/resize_2.png&quot;;
import cancel from &quot;../assets/cancel.png&quot;;
var cancel_x = null;
var cancel_y = null;
var resize_v_x = null;
var resize_v_y = null;
var resize_x = null;
var resize_y = null;
var rotate_x = null;
var rotate_y = null;
function Design() {
const [isHovered_t, setIsHovered_t] = useState(false);
const [isHovered_i, setIsHovered_i] = useState(false);
const [isHovered_c, setIsHovered_c] = useState(false);
const [isHovered_tg, setIsHovered_tg] = useState(false);
const [isHovered_ig, setIsHovered_ig] = useState(false);
const [isHovered_cg, setIsHovered_cg] = useState(false);
const [fontSize, setFontSize] = useState(10);
const [outlineWidth, setOutlineWidth] = useState(0);
const [rotate, setRotate] = useState(0);
const [soleColor, setSoleColor] = useState(right_w);
const [shoeSide, setShoeSide] = useState(&quot;right&quot;);
const [imageSize, setImageSize] = useState({ x: 100, y: 100 });
const [imageSizes, setImageSizes] = useState([]);
const [images, setImages] = useState([]);
const [imagePositions, setImagePositions] = useState([]);
var targetImage;
const [strapColor, setStrapColor] = useState(&quot;black&quot;);
const [rotationAngle, setRotationAngle] = useState(0);
const [isRotating, setIsRotating] = useState(false);
const [initialAngle, setInitialAngle] = useState(0);
var resize_v_s = false;
const canvasRef = useRef(null);
var animationFrame;
const quick_draw = () =&gt; {
const canvas = canvasRef.current;
const ctx = canvas.getContext(&#39;2d&#39;);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = strapColor; // Assuming you have a strapColor state to hold the selected strap color
ctx.fillRect(0, 0, canvas.width, canvas.height);
images.forEach((imageUrl, i) =&gt; {
const canvas = canvasRef.current;
const ctx = canvas.getContext(&#39;2d&#39;);
const image = new Image();
image.src = imageUrl;
image.onload = () =&gt; {
ctx.drawImage(image, imagePositions[i].x, imagePositions[i].y, imageSizes[i].x, imageSizes[i].y);
};
});
}
const draw_image = () =&gt; {
console.log(images);
const canvas = canvasRef.current;
const ctx = canvas.getContext(&#39;2d&#39;);
const image_loading = false;
console.log(&quot;Rotating State : &quot;, isRotating);
if (isRotating === false) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = strapColor; // Assuming you have a strapColor state to hold the selected strap color
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
// Check if all images are loaded
const allImagesLoaded = images.every((imageUrl) =&gt; {
return imageUrl in imageCache;
});
if (!allImagesLoaded) {
// If not all images are loaded, wait for the next animation frame to redraw
animationFrame = requestAnimationFrame(draw_image);
return;
}
cancel_x = imagePositions[targetImage].x - 14;
cancel_y = imagePositions[targetImage].y - 14;
resize_v_x = imagePositions[targetImage].x - 14;
resize_v_y = imagePositions[targetImage].y + imageSizes[targetImage].y;
resize_x = imagePositions[targetImage].x - 5 + imageSizes[targetImage].x;
resize_y = imagePositions[targetImage].y - 5 + imageSizes[targetImage].y;
rotate_x = imagePositions[targetImage].x - 5 + imageSizes[targetImage].x;
rotate_y = imagePositions[targetImage].y - 12;
ctx.strokeRect(imagePositions[targetImage].x - 5, imagePositions[targetImage].y - 5, imageSizes[targetImage].x + 10, imageSizes[targetImage].y + 10);
const cancel_ = new Image();
cancel_.src = cancel;
const rotate_ = new Image();
rotate_.src = rotate_i;
const resize_v = new Image();
resize_v.src = resize_2;
const resize_ = new Image();
resize_.src = resize_1;
console.log(&quot;Target Image : &quot;, targetImage);
images.forEach((imageUrl, i) =&gt; {
if (!(isRotating === true &amp;&amp; i === targetImage)) {
const image = imageCache[imageUrl];
ctx.drawImage(image, imagePositions[i].x, imagePositions[i].y, imageSizes[i].x, imageSizes[i].y);
}
});
animationFrame = requestAnimationFrame(draw_image); // Request the next animation frame
ctx.drawImage(cancel_, cancel_x, cancel_y, 25, 25);
ctx.drawImage(resize_v, resize_v_x, resize_v_y, 25, 25);
ctx.drawImage(resize_, resize_x, resize_y, 25, 25);
ctx.drawImage(rotate_, rotate_x, rotate_y, 25, 25);
}
const stopDrawingImages = () =&gt; {
cancelAnimationFrame(animationFrame); // Stop the animation loop when dragging is done
animationFrame = null;
};
const imageCache = {};
const preloadImages = () =&gt; {
images.forEach((imageUrl) =&gt; {
const image = new Image();
image.src = imageUrl;
imageCache[imageUrl] = image;
});
};
useEffect(() =&gt; {
const canvas = canvasRef.current;
const ctx = canvas.getContext(&#39;2d&#39;);
ctx.fillStyle = strapColor; // Assuming you have a strapColor state to hold the selected strap color
ctx.fillRect(0, 0, canvas.width, canvas.height);
preloadImages();
images.forEach((imageUrl, i) =&gt; {
const canvas = canvasRef.current;
const ctx = canvas.getContext(&#39;2d&#39;);
const image = new Image();
image.src = imageUrl;
image.onload = () =&gt; {
ctx.drawImage(image, imagePositions[i].x, imagePositions[i].y, imageSizes[i].x, imageSizes[i].y);
};
});
}, [images, imagePositions, strapColor, imageSizes])
const handleOnMouse = (e) =&gt; {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
var scaleX = canvas.width / rect.width;    // relationship bitmap vs. element for x
var scaleY = canvas.height / rect.height;
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
if ((mouseX &gt;= cancel_x &amp;&amp;
mouseX &lt;= cancel_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= cancel_y &amp;&amp;
mouseY &lt;= cancel_y + 25) || (mouseX &gt;= resize_v_x &amp;&amp;
mouseX &lt;= resize_v_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= resize_v_y &amp;&amp;
mouseY &lt;= resize_v_y + 25) || (mouseX &gt;= resize_x &amp;&amp;
mouseX &lt;= resize_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= resize_y &amp;&amp;
mouseY &lt;= resize_y + 25) || (mouseX &gt;= rotate_x &amp;&amp;
mouseX &lt;= rotate_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= rotate_y &amp;&amp;
mouseY &lt;= rotate_y + 25)) {
const canvas_ = document.getElementById(&quot;canvas&quot;);
canvas_.style.cursor = &quot;pointer&quot;;
console.log(&quot;enter&quot;);
}
else {
const canvas_ = document.getElementById(&quot;canvas&quot;);
canvas_.style.cursor = &quot;default&quot;;
}
}
const handleMouseDown = (e) =&gt; {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
var scaleX = canvas.width / rect.width;    // relationship bitmap vs. element for x
var scaleY = canvas.height / rect.height;
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
if (targetImage != undefined) {
if (!(mouseX &gt;= imagePositions[targetImage].x &amp;&amp;
mouseX &lt;= imagePositions[targetImage].x + imageSizes[targetImage].x &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= imagePositions[targetImage].y &amp;&amp;
mouseY &lt;= imagePositions[targetImage].y + imageSizes[targetImage].y) &amp;&amp; !(mouseX &gt;= cancel_x &amp;&amp;
mouseX &lt;= cancel_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= cancel_y &amp;&amp;
mouseY &lt;= cancel_y + 25) &amp;&amp; !(mouseX &gt;= resize_v_x &amp;&amp;
mouseX &lt;= resize_v_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= resize_v_y &amp;&amp;
mouseY &lt;= resize_v_y + 25) &amp;&amp; !(mouseX &gt;= resize_x &amp;&amp;
mouseX &lt;= resize_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= resize_y &amp;&amp;
mouseY &lt;= resize_y + 25) &amp;&amp; !(mouseX &gt;= rotate_x &amp;&amp;
mouseX &lt;= rotate_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= rotate_y &amp;&amp;
mouseY &lt;= rotate_y + 25)) {
console.log(mouseX, mouseY);
console.log(cancel_x, cancel_y);
quick_draw();
}
}
if ((mouseX &gt;= cancel_x &amp;&amp;
mouseX &lt;= cancel_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= cancel_y &amp;&amp;
mouseY &lt;= cancel_y + 25)) {
setImages(prevState =&gt; prevState.filter((_, index) =&gt; index !== targetImage));
setImagePositions(prevState =&gt; prevState.filter((_, index) =&gt; index !== targetImage));
setImageSizes(prevState =&gt; prevState.filter((_, index) =&gt; index !== targetImage));
preloadImages();
}
if ((mouseX &gt;= resize_v_x &amp;&amp;
mouseX &lt;= resize_v_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= resize_v_y &amp;&amp;
mouseY &lt;= resize_v_y + 25)) {
canvas.addEventListener(&#39;mousemove&#39;, handleResizeZ);
canvas.addEventListener(&#39;mouseup&#39;, handleMouseUp);
}
if ((mouseX &gt;= resize_x &amp;&amp;
mouseX &lt;= resize_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= resize_y &amp;&amp;
mouseY &lt;= resize_y + 25)) {
canvas.addEventListener(&#39;mousemove&#39;, handleResize);
canvas.addEventListener(&#39;mouseup&#39;, handleMouseUp);
}
if ((mouseX &gt;= rotate_x &amp;&amp;
mouseX &lt;= rotate_x + 25 &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= rotate_y &amp;&amp;
mouseY &lt;= rotate_y + 25)) {
setIsRotating(true);
canvas.addEventListener(&#39;mousemove&#39;, handleRotate);
canvas.addEventListener(&#39;mouseup&#39;, handleMouseUp);
}
// Check if the mouse is within the image boundaries
imagePositions.forEach((pos, i) =&gt; {
if (
mouseX &gt;= imagePositions[i].x &amp;&amp;
mouseX &lt;= imagePositions[i].x + imageSizes[i].x &amp;&amp; // Width of the image (you can adjust this value based on the image size)
mouseY &gt;= imagePositions[i].y &amp;&amp;
mouseY &lt;= imagePositions[i].y + imageSizes[i].y // Height of the image (you can adjust this value based on the image size)
) {
//setTargetImage(i);
const ctx = canvas.getContext(&#39;2d&#39;);
targetImage = i;
ctx.strokeStyle = &quot;blue&quot;;
ctx.strokeRect(imagePositions[i].x - 5, imagePositions[i].y - 5, imageSizes[i].x + 10, imageSizes[i].y + 10);
cancel_x = imagePositions[i].x - 14;
cancel_y = imagePositions[i].y - 14;
resize_v_x = imagePositions[i].x - 14;
resize_v_y = imagePositions[i].y + imageSizes[i].y;
resize_x = imagePositions[i].x - 5 + imageSizes[i].x;
resize_y = imagePositions[i].y - 5 + imageSizes[i].y;
rotate_x = imagePositions[i].x - 5 + imageSizes[i].x;
rotate_y = imagePositions[i].y - 12;
const cancel_ = new Image();
cancel_.src = cancel;
const resize_v = new Image();
resize_v.src = resize_2;
const resize_ = new Image();
resize_.src = resize_1;
const rotate_ = new Image();
rotate_.src = rotate_i;
rotate_.onload = () =&gt; {
ctx.drawImage(rotate_, rotate_x, rotate_y, 25, 25);
}
resize_.onload = () =&gt; {
ctx.drawImage(resize_, resize_x, resize_y, 25, 25);
}
resize_v.onload = () =&gt; {
ctx.drawImage(resize_v, resize_v_x, resize_v_y, 25, 25);
}
cancel_.onload = () =&gt; {
ctx.drawImage(cancel_, cancel_x, cancel_y, 25, 25);
}
console.log(targetImage);
console.log(&quot;match&quot;, targetImage);
// If the mouse is inside the image, initiate dragging
canvas.addEventListener(&#39;mousemove&#39;, handleMouseMove);
canvas.addEventListener(&#39;mouseup&#39;, handleMouseUp);
const canvas_ = document.getElementById(&quot;canvas&quot;);
canvas_.style.cursor = &quot;move&quot;;
}
})
};
const handleRotate = (e) =&gt; {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
var scaleX = canvas.width / rect.width; // relationship bitmap vs. element for x
var scaleY = canvas.height / rect.height;
const ctx = canvas.getContext(&quot;2d&quot;);
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
const centerX = imagePositions[targetImage].x + imageSizes[targetImage].x / 2; // Assuming the image&#39;s center is at (150, 100)
const centerY = imagePositions[targetImage].y - imageSizes[targetImage].y / 2;
const deltaX = mouseX - centerX;
const deltaY = mouseY - centerY;
const angle = Math.atan2(deltaY, deltaX);
setRotationAngle(angle);
ctx.fillStyle = strapColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const image = new Image();
image.src = images[targetImage];
image.onload = () =&gt; {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(angle);
const pos = imagePositions;
pos[targetImage] = { x: -imageSizes[targetImage].x / 2, y: -imageSizes[targetImage].y / 2 };
setImagePositions(imagePositions);
ctx.drawImage(
image,
-imageSizes[targetImage].x / 2,
-imageSizes[targetImage].y / 2,
imageSizes[targetImage].x,
imageSizes[targetImage].y
);
ctx.restore();
};
}
const handleResize = (e) =&gt; {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
var scaleX = canvas.width / rect.width;    // relationship bitmap vs. element for x
var scaleY = canvas.height / rect.height;
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
var imgSize = imageSizes;
imgSize[targetImage] = { x: mouseX, y: mouseY };
setImageSizes(imgSize);
if (!animationFrame) {
// Request animation frame only if it&#39;s not already requested
animationFrame = requestAnimationFrame(draw_image);
}
}
const handleResizeZ = (e) =&gt; {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
var scaleX = canvas.width / rect.width;    // relationship bitmap vs. element for x
var scaleY = canvas.height / rect.height;
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
var imgSize = imageSizes;
imgSize[targetImage] = { x: imgSize[targetImage].x, y: mouseY };
setImageSizes(imgSize);
if (!animationFrame) {
// Request animation frame only if it&#39;s not already requested
animationFrame = requestAnimationFrame(draw_image);
}
}
const handleMouseMove = (e) =&gt; {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
var scaleX = canvas.width / rect.width;    // relationship bitmap vs. element for x
var scaleY = canvas.height / rect.height;
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
var pos = imagePositions;
pos[targetImage] = {
x: mouseX - 50, // Half of the width of the image
y: mouseY - 50
}
setImagePositions(pos);
if (!animationFrame) {
// Request animation frame only if it&#39;s not already requested
animationFrame = requestAnimationFrame(draw_image);
}
};
const handleMouseUp = () =&gt; {
const canvas = canvasRef.current;
// Remove the event listeners when dragging is done
canvas.removeEventListener(&#39;mousemove&#39;, handleMouseMove);
canvas.removeEventListener(&#39;mouseup&#39;, handleMouseUp);
canvas.removeEventListener(&#39;mousemove&#39;, handleResizeZ);
canvas.removeEventListener(&#39;mousemove&#39;, handleResize);
canvas.removeEventListener(&#39;mousemove&#39;, handleRotate);
setIsRotating(false);
const canvas_ = document.getElementById(&quot;canvas&quot;);
canvas_.style.cursor = &quot;default&quot;;
stopDrawingImages();
resize_v_s = false;
};
const handleImageUpload = (event) =&gt; {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const imageDataUrl = e.target.result;
// Use the imageDataUrl for further processing (e.g., display image or upload to server)
setImages((prev) =&gt; [...prev, imageDataUrl]);
setImagePositions((prev) =&gt; [...prev, { x: 50, y: 50 }]);
setImageSizes((prev) =&gt; [...prev, { x: 100, y: 100 }]);
};
reader.readAsDataURL(file);
}
};
return (
&lt;&gt;
&lt;Navbar /&gt;
&lt;div id=&quot;designContainer&quot;&gt;
&lt;div id=&quot;canvasContainer&quot;&gt;
&lt;img src={soleColor} alt=&quot;black slippers&quot; /&gt;
&lt;canvas onMouseMove={handleOnMouse} onMouseDown={handleMouseDown} ref={canvasRef} id=&quot;canvas&quot;&gt;
&lt;p&gt;Hello, I am canvas&lt;/p&gt;
&lt;/canvas&gt;
&lt;/div&gt;
&lt;/&gt;
);
}
export default Design;

I am using React JS along with HTML5 Canvas, I am have a canvas in which images are uploaded, on clicking and image, a box appears around the picture selected with 4 icons for rotate, resize Vericaly, close and resize overall, all the icons are working perfectly but the rotation is not perfect, when I click on the rotate icon and move the mouse, the image first moves upwards and then rotate around its center and it cannot be clicked again as its position in the canvas goes wrong. The handleRotate function handles the image rotation when the mouse button is pressed and the mouse is moved.

答案1

得分: 0

所以,我没有正确居中画布,画布没有居中在目标图像的中心,因为我从位置中减去了值。

英文:

So, I was not properly centering the canvas, the canvas was not being centered at the centre of the target image as I was subtracting from the position.

huangapple
  • 本文由 发表于 2023年8月10日 18:47:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定