Skip to content
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 8 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 167 additions & 0 deletions apps/client/app/features/artboard/bucketFill.ts
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[][],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
data: Color[][],
colorMap: Color[][],

とかpixelDataとかだと苦なく読める

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR 出してるし前言ったけど bucketFill は修正しないね

向こうでも data 使ってるからそっちに書いてくれ

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);
}
30 changes: 30 additions & 0 deletions apps/client/app/features/artboard/index.tsx
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;
}
`;
30 changes: 30 additions & 0 deletions apps/client/app/features/artboard/types.ts
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;
135 changes: 135 additions & 0 deletions apps/client/app/features/artboard/useArtboard.ts
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

時間的にnextなのは分かるがprevだろみたいな気もする

Copy link
Member Author

Choose a reason for hiding this comment

The 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,
};
}
Loading