-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
🎉 お絵かきキャンバス実装 #8
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
6c7fe0d
🎉 お絵かきキャンバス実装
SSlime-s 3ef8242
🎨 何があっても端で途切れないように
SSlime-s aefcce5
🎨 塗りつぶしの色の範囲広げる
SSlime-s 323ac25
♻️ ロックしてるときの処理を data attribute に移す
SSlime-s 02a0d71
♻️ mouse out を mouse leave に
SSlime-s 66bd044
✨ でもページのツール選択をラジオボタンに
SSlime-s 12a42aa
👕 fmt
SSlime-s 79f2108
♻️ colorCode を明示
SSlime-s File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
// ref: https://github.com/cat-crosswalk/nascalay-frontend/blob/main/src/components/Canvas/bucketFill.ts | ||
|
||
import type { Color, LikeEqualColor } from "./types"; | ||
import { colorsToRaw, equalColor, hexToColor, rawToColors } from "./utils"; | ||
|
||
// https://nullpon.moe/dev/sample/canvas/bucketfill.html めちゃめちゃ参考にしてる | ||
// シードフィルアルゴリズムで塗りつぶす | ||
|
||
/** | ||
* 指定された座標から右方向にまっすぐ targetColor と等しい色を塗りつぶす | ||
* | ||
* @returns 右端の x 座標 | ||
*/ | ||
function drawToRight( | ||
data: Color[][], | ||
x: number, | ||
y: number, | ||
color: Color, | ||
widthRange: readonly [number, number], | ||
ras0q marked this conversation as resolved.
Show resolved
Hide resolved
|
||
targetColor: Color, | ||
likeEqualColor: LikeEqualColor, | ||
ras0q marked this conversation as resolved.
Show resolved
Hide resolved
|
||
) { | ||
let rightEnd = null; | ||
for (let nowX = x + 1; nowX < widthRange[1]; nowX++) { | ||
const nowColor = data[y][nowX]; | ||
if (!likeEqualColor(nowColor, targetColor)) break; | ||
data[y][nowX] = color; | ||
rightEnd = nowX; | ||
} | ||
return rightEnd; | ||
} | ||
|
||
/** | ||
* 指定された座標から左方向にまっすぐ targetColor と等しい色を塗りつぶす | ||
* | ||
* @returns 左端の x 座標 | ||
*/ | ||
function drawToLeft( | ||
data: Color[][], | ||
x: number, | ||
y: number, | ||
color: Color, | ||
widthRange: readonly [number, number], | ||
targetColor: Color, | ||
likeEqualColor: LikeEqualColor, | ||
) { | ||
let leftEnd = null; | ||
for (let nowX = x; nowX >= widthRange[0]; nowX--) { | ||
const nowColor = data[y][nowX]; | ||
if (!likeEqualColor(nowColor, targetColor)) break; | ||
data[y][nowX] = color; | ||
leftEnd = nowX; | ||
} | ||
return leftEnd; | ||
} | ||
|
||
/** | ||
* seeds を破壊的に更新する | ||
*/ | ||
function updateSeeds( | ||
ras0q marked this conversation as resolved.
Show resolved
Hide resolved
|
||
data: Readonly<Color[][]>, | ||
xLeft: number, | ||
xRight: number, | ||
y: number, | ||
seeds: { x: number; y: number }[], | ||
targetColor: Color, | ||
heightRange: readonly [number, number], | ||
likeEqualColor: LikeEqualColor, | ||
) { | ||
if (y < heightRange[0] || y >= heightRange[1]) return; | ||
|
||
let prevIsTarget = false; | ||
for (let nowX = xLeft; nowX <= xRight; nowX++) { | ||
const nowColor = data[y][nowX]; | ||
if (likeEqualColor(nowColor, targetColor)) { | ||
if (!prevIsTarget) { | ||
seeds.push({ x: nowX, y }); | ||
} | ||
prevIsTarget = true; | ||
} else { | ||
prevIsTarget = false; | ||
} | ||
} | ||
ras0q marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
export function bucketFill( | ||
canvas: HTMLCanvasElement, | ||
x: number, | ||
y: number, | ||
colorCode: `#${string}`, | ||
widthRange?: [number, number], | ||
heightRange?: [number, number], | ||
likeEqualColor: LikeEqualColor = equalColor, | ||
) { | ||
const ctx = canvas.getContext("2d"); | ||
if (ctx === null) { | ||
return; | ||
} | ||
|
||
const width = canvas.width; | ||
const height = canvas.height; | ||
const imageData = ctx.getImageData(0, 0, width, height); | ||
const data = imageData.data; | ||
const formattedData = rawToColors(data, width, height); | ||
const targetColor = formattedData[y][x]; | ||
const color = hexToColor(colorCode); | ||
if (color === null) { | ||
console.error("invalid color"); | ||
return; | ||
} | ||
if (likeEqualColor(color, targetColor)) return; | ||
|
||
const xRange = widthRange ?? [0, width]; | ||
const yRange = heightRange ?? [0, height]; | ||
|
||
const seeds = [{ x, y }]; | ||
while (seeds.length > 0) { | ||
// biome-ignore lint/style/noNonNullAssertion: while の条件式から pop は undefined にならない | ||
const { x, y } = seeds.pop()!; | ||
|
||
// 左右に塗りつぶす | ||
const leftX = | ||
drawToLeft( | ||
formattedData, | ||
x, | ||
y, | ||
color, | ||
xRange, | ||
targetColor, | ||
likeEqualColor, | ||
) ?? x; | ||
const rightX = | ||
drawToRight( | ||
formattedData, | ||
x, | ||
y, | ||
color, | ||
xRange, | ||
targetColor, | ||
likeEqualColor, | ||
) ?? x; | ||
|
||
updateSeeds( | ||
formattedData, | ||
leftX, | ||
rightX, | ||
y + 1, | ||
seeds, | ||
targetColor, | ||
yRange, | ||
likeEqualColor, | ||
); | ||
updateSeeds( | ||
formattedData, | ||
leftX, | ||
rightX, | ||
y - 1, | ||
seeds, | ||
targetColor, | ||
yRange, | ||
likeEqualColor, | ||
); | ||
} | ||
|
||
imageData.data.set(colorsToRaw(formattedData, width, height)); | ||
ctx.putImageData(imageData, 0, 0); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { boolAttr } from "@/utils/boolAttr"; | ||
import styled from "@emotion/styled"; | ||
import type { RefObject } from "react"; | ||
import type { MouseHandlers } from "./types"; | ||
|
||
interface Props { | ||
canvasRef: RefObject<HTMLCanvasElement>; | ||
mouseHandlers: MouseHandlers; | ||
isLocked?: boolean; | ||
} | ||
|
||
export function Artboard({ canvasRef, mouseHandlers, isLocked }: Props) { | ||
return ( | ||
<Canvas | ||
ref={canvasRef} | ||
width={640} | ||
height={480} | ||
{...mouseHandlers} | ||
data-is-locked={boolAttr(isLocked)} | ||
/> | ||
); | ||
} | ||
|
||
const Canvas = styled.canvas` | ||
border: 1px solid black; | ||
|
||
&[data-is-locked] { | ||
pointer-events: none; | ||
} | ||
`; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
export const penTypes = ["pen", "eraser", "bucket"] as const; | ||
export type PenType = (typeof penTypes)[number]; | ||
|
||
export interface Pos { | ||
x: number; | ||
y: number; | ||
} | ||
|
||
export type MouseHandlers = Required< | ||
Pick< | ||
React.DOMAttributes<HTMLElement>, | ||
| "onMouseDown" | ||
| "onMouseMove" | ||
| "onMouseUp" | ||
| "onMouseLeave" | ||
| "onMouseEnter" | ||
> | ||
>; | ||
|
||
/** | ||
* 色を扱いやすくするための型 | ||
* r, g, b, a はそれぞれ 0 から 255 の範囲の整数 | ||
*/ | ||
export interface Color { | ||
r: number; | ||
g: number; | ||
b: number; | ||
a: number; | ||
} | ||
export type LikeEqualColor = (a: Color, b: Color) => boolean; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
import type React from "react"; | ||
import { type RefObject, useCallback, useRef } from "react"; | ||
import type { MouseHandlers, Pos } from "./types"; | ||
import { useHistory } from "./useHistory"; | ||
import { type PenData, useSketch } from "./useSketch"; | ||
import { type CanvasData, applyCanvasData, getCanvasData } from "./utils"; | ||
|
||
interface Handler { | ||
clear(): void; | ||
undo(): void; | ||
redo(): void; | ||
resetCanvas(): void; | ||
shortcut(e: React.KeyboardEvent): void; | ||
exportDataURL(): string; | ||
canRedo: boolean; | ||
canUndo: boolean; | ||
mouseHandlers: MouseHandlers; | ||
} | ||
|
||
interface State { | ||
lastPos: Pos | null; | ||
} | ||
const createInitialState = (): State => ({ | ||
lastPos: null, | ||
}); | ||
|
||
export function useArtboard( | ||
canvasRef: RefObject<HTMLCanvasElement>, | ||
penData: PenData, | ||
): Handler { | ||
// NOTE: initial state が重くなる場合は https://ja.react.dev/reference/react/useRef#avoiding-recreating-the-ref-contents のようにする | ||
const state = useRef<State>(createInitialState()); | ||
const { | ||
canRedo, | ||
canUndo, | ||
clearHistory, | ||
pushHistory, | ||
undoHistory, | ||
redoHistory, | ||
} = useHistory<CanvasData>(); | ||
const { mouseHandlers } = useSketch(canvasRef, penData, pushHistory); | ||
|
||
const resetCanvas = useCallback(() => { | ||
const canvas = canvasRef.current; | ||
if (canvas === null) return; | ||
const ctx = canvas.getContext("2d"); | ||
if (ctx === null) return; | ||
|
||
ctx.clearRect(0, 0, canvas.width, canvas.height); | ||
state.current = createInitialState(); | ||
|
||
clearHistory(); | ||
}, [canvasRef.current, clearHistory]); | ||
|
||
const saveCanvas = useCallback(() => { | ||
const canvas = canvasRef.current; | ||
if (canvas === null) return; | ||
|
||
const savedData = getCanvasData(canvas); | ||
if (savedData === null) return; | ||
|
||
pushHistory(savedData); | ||
}, [canvasRef.current, pushHistory]); | ||
|
||
const undo = useCallback(() => { | ||
const canvas = canvasRef.current; | ||
if (canvas === null) return; | ||
|
||
const now = getCanvasData(canvas); | ||
if (now === null) return; | ||
|
||
const next = undoHistory(now); | ||
if (next === null) return; | ||
Comment on lines
+72
to
+73
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 時間的にnextなのは分かるがprevだろみたいな気もする There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 次に適用するって意味で next ね |
||
|
||
applyCanvasData(canvas, next); | ||
}, [canvasRef.current, undoHistory]); | ||
|
||
const redo = useCallback(() => { | ||
const canvas = canvasRef.current; | ||
if (canvas === null) return; | ||
|
||
const now = getCanvasData(canvas); | ||
if (now === null) return; | ||
|
||
const next = redoHistory(now); | ||
if (next === undefined) return; | ||
|
||
applyCanvasData(canvas, next); | ||
}, [canvasRef.current, redoHistory]); | ||
|
||
const clear = useCallback(() => { | ||
const canvas = canvasRef.current; | ||
if (canvas === null) return; | ||
|
||
saveCanvas(); | ||
|
||
const ctx = canvas.getContext("2d"); | ||
if (ctx === null) return; | ||
|
||
ctx.clearRect(0, 0, canvas.width, canvas.height); | ||
}, [canvasRef.current, saveCanvas]); | ||
|
||
const shortcut = useCallback( | ||
(e: React.KeyboardEvent) => { | ||
// NOTE: shift を押した状態だと e.key が大文字になるので小文字に変換してから比較する | ||
if (e.key.toLocaleLowerCase() === "z" && (e.ctrlKey || e.metaKey)) { | ||
if (e.shiftKey) { | ||
redo(); | ||
} else { | ||
undo(); | ||
} | ||
} | ||
ras0q marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, | ||
[redo, undo], | ||
); | ||
|
||
const exportDataURL = useCallback(() => { | ||
const canvas = canvasRef.current; | ||
if (canvas === null) return ""; | ||
|
||
return canvas.toDataURL(); | ||
}, [canvasRef.current]); | ||
|
||
return { | ||
clear, | ||
undo, | ||
redo, | ||
resetCanvas, | ||
shortcut, | ||
exportDataURL, | ||
canRedo, | ||
canUndo, | ||
mouseHandlers, | ||
}; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
とか
pixelData
とかだと苦なく読めるThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
PR 出してるし前言ったけど bucketFill は修正しないね
向こうでも data 使ってるからそっちに書いてくれ