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

feat: support paste image #197

Merged
merged 1 commit into from
Oct 12, 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
50 changes: 49 additions & 1 deletion packages/core/src/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,14 @@ import {
import { generateNKeysBetween } from 'fractional-indexing';

import { type SuikaEditor } from './editor';
import { type GraphicsAttrs, isFrameGraphics, SuikaGraphics } from './graphics';
import {
type GraphicsAttrs,
isFrameGraphics,
SuikaGraphics,
SuikaRect,
} from './graphics';
import { isCanvasGraphics } from './graphics/canvas';
import { PaintType } from './paint';
import { toSVG } from './to_svg';
import { Transaction } from './transaction';
import { type IEditorPaperData } from './type';
Expand Down Expand Up @@ -46,6 +52,21 @@ export class ClipboardManager {
) {
return;
}

if (clipboardData.files.length > 0) {
for (const file of clipboardData.files) {
if (file.type.includes('image')) {
const reader = new FileReader();
reader.onload = (e) => {
const base64 = e.target?.result as string;
this.createGraphicsWithImg(base64);
};
reader.readAsDataURL(file);
}
}
return;
}

const pastedData = clipboardData.getData('Text');
this.addGraphsFromClipboard(pastedData);
};
Expand All @@ -64,6 +85,33 @@ export class ClipboardManager {
};
}

private async createGraphicsWithImg(imgUrl: string) {
const editor = this.editor;
await editor.imgManager.addImg(imgUrl);
const img = editor.imgManager.getImg(imgUrl);
const center = editor.viewportManager.getCenter();
if (img) {
const rectGraphics = new SuikaRect(
{
objectName: '',
width: img.width,
height: img.height,
fill: [{ type: PaintType.Image, attrs: { src: imgUrl } }],
},
{
advancedAttrs: {
x: center.x - img.width / 2,
y: center.y - img.height / 2,
},
doc: editor.doc,
},
);
editor.sceneGraph.addItems([rectGraphics]);
editor.doc.getCanvas().insertChild(rectGraphics);
editor.render();
}
}

copy() {
const snapshot = this.getSelectedItemsSnapshot();
if (!snapshot) {
Expand Down
Loading