ドラッグアンドドロップ機能を追加する
目的:パズルピースのドラッグアンドドロップのロジックを実装する。
- ドラッグ開始、ドラッグオーバー、およびドロップイベントのハンドラを追加する。
- ドロップ時にパズルピースを交換するロジックを実装する。
// src/components/PuzzleGame.js
const PuzzleGame = () => {
//...前のコード
// ドラッグイベントの開始を処理する
const handleDragStart = (e, position) => {
e.dataTransfer.setData("text/plain", position);
};
// ドロップイベントを処理する
const handleDrop = (e, position) => {
e.preventDefault();
const originalPosition = e.dataTransfer.getData("text");
// ここにパズルピースの位置を交換するロジックを追加する
setPositions((prevPositions) => {
const newPos = [...prevPositions];
[newPos[originalPosition], newPos[position]] = [
newPos[position],
newPos[originalPosition]
];
return newPos;
});
};
// 既定の動作を防止することでドロップアクションを許可する
const handleDragOver = (e) => {
e.preventDefault();
};
// 追加されたドラッグアンドドロップハンドラ付きでパズルピースをレンダリングする
};
// src/components/PuzzleGame.js
const PuzzleGame = () => {
//...前のコード
return (
<div className="game-container">
<div className="reference-image">
<img src={imgUrl} alt="Reference Image" />
</div>
<div className="puzzle-container">
{positions.map((pos, index) => {
const x = (pos % 4) * 100;
const y = Math.floor(pos / 4) * 100;
return (
<div
key={index}
className="puzzle-piece"
draggable
onDragStart={(e) => handleDragStart(e, index)}
onDrop={(e) => handleDrop(e, index)}
onDragOver={handleDragOver}
style={{
backgroundImage: `url('${imgUrl}')`,
backgroundPosition: `-${x}px -${y}px`
}}
/>
);
})}
</div>
</div>
);
};