基于 yjs 实现实时在线多人协作的绘画功能

- 支持多客户端实时共享编辑
- 自动同步,离线支持
- 自动合并,自动冲突处理
1. 客户端代码(基于Vue3)
实现绘画功能
<template>
<div style="{width: 100vw; height: 100vh; overflow: hidden;}">
<canvas ref="canvasRef" style="{border: solid 1px red;}" @mousedown="startDrawing" @mousemove="draw"
@mouseup="stopDrawing" @mouseleave="stopDrawing">
</canvas>
</div>
<div style="position: absolute; bottom: 10px; display: flex; justify-content: center; height: 40px; width: 100vw;">
<div style="width: 100px; height: 40px; display: flex; align-items: center; justify-content: center; color: white;"
:style="{ backgroundColor: color }">
<span>当前颜色</span>
</div>
<Button style="width: 100px; height: 40px; margin-left: 10px;" @click="switchMode(DrawType.Point)">画点</Button>
<Button style="width: 100px; height: 40px; margin-left: 10px;" @click="switchMode(DrawType.Line)">直线</Button>
<Button style="width: 100px; height: 40px; margin-left: 10px;" @click="switchMode(DrawType.Draw)">涂鸦</Button>
<Button style="width: 100px; height: 40px; margin-left: 10px;" @click="clearCanvas">清除</Button>
</div>
</template>
<script setup lang="ts">
import {
ref, onMounted } from 'vue';
import {
Button, Modal, Input } from "ant-design-vue";
import * as Y from 'yjs';
import {
WebsocketProvider } from 'y-websocket';
import {
v4 as uuidv4 } from 'uuid';
const canvasRef = ref<null | HTMLCanvasElement>(null);
const ctx = ref<CanvasRenderingContext2D | null>(null);
const drawing = ref(false);
const color = ref<string>("black");
class Point {
x: number = 0.0;
y: number = 0.0;
}
enum DrawType {
None,
Point,
Line,
Draw,
}
const colors = [
"#FF5733", "#33FF57", "#5733FF", "#FF33A2", "#A2FF33",
"#33A2FF", "#FF33C2", "#C2FF33", "#33C2FF", "#FF3362",
"#6233FF", "#FF336B", "#6BFF33", "#33FFA8", "#A833FF",
"#33FFAA", "#AA33FF", "#FFAA33", "#33FF8C", "#8C33FF"
];
// 随机选择一个颜色
function getRandomColor() {
const randomIndex = Math.floor(Math.random() * colors.length);
return colors[randomIndex];
}
class DrawElementProp {
color: string = "black";
}
class DrawElement {
id: string = "";
version: string = "";
type: DrawType = DrawType.None;
geometry: Point[] = [];
properties: DrawElementProp = new DrawElementProp();
}
// 选择的绘画模式
const drawMode = ref<DrawType>(DrawType.Draw);
// 定义变量来跟踪第一个点的坐标和鼠标是否按下
const point = ref<Point | null>(null);
// 创建 ydoc, websocketProvider
const ydoc = new Y.Doc();
// 创建一个 Yjs Map,用于存储绘图数据
基于yjs的实时在线多人协作绘画应用开发

本文介绍了如何使用yjs和Vue3构建一个支持多客户端实时共享编辑的在线绘画应用,包括绘画模式切换、实时同步和冲突处理功能,同时涉及服务端的简单实现和数据持久化的客户端设计。
最低0.47元/天 解锁文章
1110





