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

[#98] Feat: 복사 짤 util 함수 구현 #100

Merged
merged 6 commits into from
Mar 5, 2024
Merged
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
59 changes: 59 additions & 0 deletions src/utils/copyZzal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { toast } from "react-toastify";
import axios from "axios";

const copyToClipboard = (pngBlob: Blob) => {
try {
navigator.clipboard.write([
new ClipboardItem({
[pngBlob.type]: pngBlob,
}),
]);
toast.success("성공적으로 복사되었습니다.");
} catch (error) {
toast.error("복사에 실패했습니다.");
console.error(error);
}
};

const copyImageToClipboard = (imageBlob: Blob) => {
const image = new Image();
image.src = URL.createObjectURL(imageBlob);

image.onload = () => {
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;

const ctx = canvas.getContext("2d");

if (!ctx) {
console.error("Canvas context를 생성할 수 없습니다.");
return;
}

ctx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight);
canvas.toBlob((blob) => {
if (blob) {
copyToClipboard(blob);
return;
}

console.error("Canvas to Blob 변환 실패");
}, "image/png");
};

image.onerror = () => {
console.error("이미지 로딩 실패");
};
};

export const copyZzal = async (imageUrl: string) => {
try {
const { data: imageBlob } = await axios.get<Blob>(imageUrl, { responseType: "blob" });

copyImageToClipboard(imageBlob);
} catch (error) {
toast.error("복사에 실패했습니다.");
console.error(error);
choi-ik marked this conversation as resolved.
Show resolved Hide resolved
}
};
Loading