aboard-overlay 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js ADDED
@@ -0,0 +1,963 @@
1
+ /**
2
+ * Aboard Overlay 内核
3
+ * 框架无关的透明标注画板,可挂载到任意宿主元素(默认 document.body)。
4
+ *
5
+ * 设计要点:
6
+ * - 背景层与绘图层分离:橡皮擦用 destination-out 擦除笔迹,擦掉后露出背景层,
7
+ * 背景为 transparent 时露出的就是下层窗口(PPT 等)。
8
+ * - 指针事件 + getCoalescedEvents 采集轨迹,多种画笔按线段渲染。
9
+ * - 所有 DOM 与样式前缀为 aboard-,避免污染宿主页面。
10
+ */
11
+
12
+ const PEN_TYPES = ['normal', 'pencil', 'ballpoint', 'fountain', 'brush', 'marker'];
13
+
14
+ const PEN_ALPHA = {
15
+ normal: 1,
16
+ pencil: 0.7,
17
+ ballpoint: 0.9,
18
+ fountain: 1,
19
+ brush: 0.85,
20
+ marker: 0.45
21
+ };
22
+
23
+ const PEN_WIDTH_FACTOR = {
24
+ normal: 1,
25
+ pencil: 1,
26
+ ballpoint: 1,
27
+ fountain: 1,
28
+ brush: 1.5,
29
+ marker: 2.2
30
+ };
31
+
32
+ const COLOR_ON_BLACKBOARD = '#ffffff';
33
+ const COLOR_ON_TRANSPARENT = '#111111';
34
+ const MIN_POINT_DISTANCE = 0.6;
35
+ const MAX_DPR = 3;
36
+ const HEX_COLOR = /^#[0-9a-f]{6}$/i;
37
+ const DEFAULT_STORAGE_KEY = 'aboard-overlay-settings-v1';
38
+
39
+ const DEFAULTS = {
40
+ tool: 'pen',
41
+ penType: 'normal',
42
+ color: COLOR_ON_TRANSPARENT,
43
+ penSize: 5,
44
+ eraserSize: 40,
45
+ background: 'transparent',
46
+ autoColor: true
47
+ };
48
+
49
+ const PEN_PRESETS = [
50
+ {
51
+ type: 'normal',
52
+ label: '普通',
53
+ icon: '<path d="M12 19l7-7 3 3-7 7-3-3z"></path><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"></path><path d="M2 2l7.586 7.586"></path><circle cx="11" cy="11" r="2"></circle>'
54
+ },
55
+ {
56
+ type: 'pencil',
57
+ label: '铅笔',
58
+ icon: '<path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path>'
59
+ },
60
+ {
61
+ type: 'ballpoint',
62
+ label: '圆珠笔',
63
+ icon: '<path d="M15.5 3l5 5L7 21.5 2 22l.5-5L15.5 3z"></path><line x1="14" y1="6" x2="18" y2="10"></line>'
64
+ },
65
+ {
66
+ type: 'fountain',
67
+ label: '钢笔',
68
+ icon: '<path d="M20 2l2 2-8 8-2-2 8-8z"></path><path d="M12 12c-2 2-4 6-4 8h8c0-2-2-6-4-8z"></path>'
69
+ },
70
+ {
71
+ type: 'brush',
72
+ label: '毛笔',
73
+ icon: '<path d="M18.37 2.63L14 7l-1.59-1.59a2 2 0 00-2.82 0L8 7l9 9 1.59-1.59a2 2 0 000-2.82L17 10l4.37-4.37a2.12 2.12 0 10-3-3z"></path><path d="M9 8c-2 3-4 3.5-7 4l8 10c2-1 6-5 6-7"></path>'
74
+ },
75
+ {
76
+ type: 'marker',
77
+ label: '荧光笔',
78
+ icon: '<path d="M14 3l7 7-3 3-7-7z"></path><path d="M4 14l7 7"></path><path d="M3 21l6-2-4-4z"></path>'
79
+ }
80
+ ];
81
+
82
+ const COLOR_PRESETS = [
83
+ { color: '#ffffff', label: '白色' },
84
+ { color: '#111111', label: '黑色' },
85
+ { color: '#ff3b30', label: '红色' },
86
+ { color: '#ff9500', label: '橙色' },
87
+ { color: '#ffd60a', label: '黄色' },
88
+ { color: '#34c759', label: '绿色' },
89
+ { color: '#0a84ff', label: '蓝色' },
90
+ { color: '#af52de', label: '紫色' }
91
+ ];
92
+
93
+ const PEN_TYPE_BUTTONS_HTML = PEN_PRESETS.map(function (preset) {
94
+ return (
95
+ '<button type="button" class="aboard-pen-type-btn" data-pen-type="' +
96
+ preset.type +
97
+ '" aria-pressed="false" title="' +
98
+ preset.label +
99
+ '画笔">' +
100
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">' +
101
+ preset.icon +
102
+ '</svg>' +
103
+ '<span>' +
104
+ preset.label +
105
+ '</span>' +
106
+ '</button>'
107
+ );
108
+ }).join('');
109
+
110
+ const COLOR_BUTTONS_HTML = COLOR_PRESETS.map(function (preset) {
111
+ return (
112
+ '<button type="button" class="aboard-color-btn" data-color="' +
113
+ preset.color +
114
+ '" style="--aboard-swatch:' +
115
+ preset.color +
116
+ '" aria-pressed="false" aria-label="' +
117
+ preset.label +
118
+ '" title="' +
119
+ preset.label +
120
+ '"></button>'
121
+ );
122
+ }).join('');
123
+
124
+ const TEMPLATE =
125
+ '<main class="aboard">' +
126
+ '<div class="aboard-surface" data-surface>' +
127
+ '<canvas class="aboard-canvas" data-canvas aria-label="自由绘图区域"></canvas>' +
128
+ '</div>' +
129
+ '<div class="aboard-eraser-cursor" data-eraser-cursor aria-hidden="true"></div>' +
130
+ '<section class="aboard-panel aboard-background-switcher" data-background-switcher aria-label="背景切换">' +
131
+ '<span class="aboard-panel-title">背景</span>' +
132
+ '<div class="aboard-segmented" role="group" aria-label="背景颜色">' +
133
+ '<button type="button" class="aboard-seg-btn" data-background="blackboard" aria-pressed="false" title="黑板绿背景">' +
134
+ '<span class="aboard-swatch aboard-swatch--blackboard" aria-hidden="true"></span><span>黑板绿</span>' +
135
+ '</button>' +
136
+ '<button type="button" class="aboard-seg-btn" data-background="transparent" aria-pressed="false" title="透明背景">' +
137
+ '<span class="aboard-swatch aboard-swatch--transparent" aria-hidden="true"></span><span>透明</span>' +
138
+ '</button>' +
139
+ '</div>' +
140
+ '</section>' +
141
+ '<div class="aboard-config-area" data-config-area>' +
142
+ '<section class="aboard-panel aboard-config-panel" data-pen-config aria-label="画笔设置">' +
143
+ '<div class="aboard-config-group">' +
144
+ '<span class="aboard-config-label">画笔类型</span>' +
145
+ '<div class="aboard-pen-type-grid" role="group" aria-label="画笔类型">' +
146
+ PEN_TYPE_BUTTONS_HTML +
147
+ '</div>' +
148
+ '</div>' +
149
+ '<div class="aboard-config-group">' +
150
+ '<span class="aboard-config-label">颜色</span>' +
151
+ '<div class="aboard-color-row">' +
152
+ COLOR_BUTTONS_HTML +
153
+ '<label class="aboard-color-custom" title="自定义颜色">' +
154
+ '<input type="color" data-custom-color value="' +
155
+ COLOR_ON_TRANSPARENT +
156
+ '" aria-label="自定义颜色">' +
157
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">' +
158
+ '<path d="M20 14.66V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5.34"></path>' +
159
+ '<polygon points="18 2 22 6 12 16 8 16 8 12 18 2"></polygon>' +
160
+ '</svg>' +
161
+ '</label>' +
162
+ '</div>' +
163
+ '</div>' +
164
+ '<div class="aboard-config-group">' +
165
+ '<label class="aboard-config-label">粗细 <span data-pen-size-value>5</span> px' +
166
+ '<input type="range" class="aboard-slider" data-pen-size min="1" max="50" value="5">' +
167
+ '</label>' +
168
+ '</div>' +
169
+ '</section>' +
170
+ '<section class="aboard-panel aboard-config-panel" data-eraser-config aria-label="橡皮擦设置">' +
171
+ '<div class="aboard-config-group">' +
172
+ '<label class="aboard-config-label">橡皮大小 <span data-eraser-size-value>40</span> px' +
173
+ '<input type="range" class="aboard-slider" data-eraser-size min="10" max="150" value="40">' +
174
+ '</label>' +
175
+ '</div>' +
176
+ '<p class="aboard-config-hint">按住并拖动即可擦除笔迹,背景颜色不会被擦掉。</p>' +
177
+ '</section>' +
178
+ '</div>' +
179
+ '<nav class="aboard-panel aboard-toolbar" aria-label="工具栏">' +
180
+ '<button type="button" class="aboard-tool-btn" data-tool="pen" aria-pressed="false" title="画笔">' +
181
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">' +
182
+ '<path d="M12 19l7-7 3 3-7 7-3-3z"></path><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"></path>' +
183
+ '<path d="M2 2l7.586 7.586"></path><circle cx="11" cy="11" r="2"></circle>' +
184
+ '</svg><span>画笔</span>' +
185
+ '</button>' +
186
+ '<button type="button" class="aboard-tool-btn" data-tool="eraser" aria-pressed="false" title="橡皮擦">' +
187
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">' +
188
+ '<path d="M20 20H7L3 16 12 7 17 12"></path><path d="M7 20l5-5"></path>' +
189
+ '</svg><span>橡皮擦</span>' +
190
+ '</button>' +
191
+ '</nav>' +
192
+ '</main>';
193
+
194
+ function clamp(value, min, max) {
195
+ return Math.min(max, Math.max(min, value));
196
+ }
197
+
198
+ export class Aboard {
199
+ constructor(options) {
200
+ const opts = options || {};
201
+
202
+ this.host =
203
+ typeof opts.host === 'string' ? document.querySelector(opts.host) : opts.host || document.body;
204
+ this.storageKey = opts.storageKey || DEFAULT_STORAGE_KEY;
205
+ this.persist = opts.persist !== false;
206
+ this.onChange = typeof opts.onChange === 'function' ? opts.onChange : null;
207
+ this.destroyed = false;
208
+ this.transparentWindowApplied = false;
209
+
210
+ // 已完成的笔画(用于窗口尺寸变化后重绘)
211
+ this.strokes = [];
212
+ this.activeStroke = null;
213
+ this.activePointerId = null;
214
+
215
+ this.viewWidth = 0;
216
+ this.viewHeight = 0;
217
+ this.dpr = 1;
218
+ this.saveTimer = null;
219
+ this.resizeObserver = null;
220
+
221
+ this.settings = this._loadSettings();
222
+ this._mount();
223
+ this._applyOptions(opts);
224
+ this._bindEvents();
225
+ this._syncUI();
226
+ this._resizeCanvas();
227
+ }
228
+
229
+ /* ---------- 生命周期 ---------- */
230
+
231
+ _mount() {
232
+ const root = document.createElement('div');
233
+ root.className = 'aboard-root';
234
+ root.innerHTML = TEMPLATE;
235
+ this.host.appendChild(root);
236
+
237
+ this.root = root;
238
+ this.el = {
239
+ surface: root.querySelector('[data-surface]'),
240
+ canvas: root.querySelector('[data-canvas]'),
241
+ eraserCursor: root.querySelector('[data-eraser-cursor]'),
242
+ backgroundSwitcher: root.querySelector('[data-background-switcher]'),
243
+ configArea: root.querySelector('[data-config-area]'),
244
+ penConfig: root.querySelector('[data-pen-config]'),
245
+ eraserConfig: root.querySelector('[data-eraser-config]'),
246
+ penSize: root.querySelector('[data-pen-size]'),
247
+ penSizeValue: root.querySelector('[data-pen-size-value]'),
248
+ eraserSize: root.querySelector('[data-eraser-size]'),
249
+ eraserSizeValue: root.querySelector('[data-eraser-size-value]'),
250
+ customColor: root.querySelector('[data-custom-color]'),
251
+ toolbar: root.querySelector('.aboard-toolbar')
252
+ };
253
+ this.ctx = this.el.canvas.getContext('2d');
254
+
255
+ this.toolButtons = Array.from(root.querySelectorAll('[data-tool]'));
256
+ this.penTypeButtons = Array.from(root.querySelectorAll('[data-pen-type]'));
257
+ this.colorButtons = Array.from(root.querySelectorAll('[data-color]'));
258
+ this.backgroundButtons = Array.from(root.querySelectorAll('[data-background]'));
259
+ }
260
+
261
+ _applyOptions(opts) {
262
+ const settings = this.settings;
263
+
264
+ if (opts.tool !== undefined) settings.tool = opts.tool === 'eraser' ? 'eraser' : 'pen';
265
+ if (opts.penType !== undefined && PEN_TYPES.indexOf(opts.penType) !== -1) settings.penType = opts.penType;
266
+
267
+ const hasColor = typeof opts.color === 'string' && HEX_COLOR.test(opts.color);
268
+ if (hasColor) {
269
+ settings.color = String(opts.color).toLowerCase();
270
+ settings.autoColor = false;
271
+ }
272
+
273
+ if (opts.penSize !== undefined && opts.penSize !== null) {
274
+ settings.penSize = clamp(Number(opts.penSize) || DEFAULTS.penSize, 1, 50);
275
+ }
276
+ if (opts.eraserSize !== undefined && opts.eraserSize !== null) {
277
+ settings.eraserSize = clamp(Number(opts.eraserSize) || DEFAULTS.eraserSize, 10, 150);
278
+ }
279
+
280
+ const hasBackground = opts.background !== undefined;
281
+ this._applyBackground(hasBackground ? opts.background : settings.background, {
282
+ autoSwapColor: !hasColor && hasBackground,
283
+ sync: false,
284
+ persist: false
285
+ });
286
+
287
+ if (opts.showToolbar === false) this.setToolbarVisible(false);
288
+ if (opts.showBackgroundSwitcher === false) this.setBackgroundSwitcherVisible(false);
289
+
290
+ if (opts.transparentWindow) {
291
+ document.documentElement.classList.add('aboard-transparent-window');
292
+ this.transparentWindowApplied = true;
293
+ }
294
+ }
295
+
296
+ destroy() {
297
+ if (this.destroyed) return;
298
+ this.destroyed = true;
299
+
300
+ clearTimeout(this.saveTimer);
301
+ if (this.resizeObserver) this.resizeObserver.disconnect();
302
+
303
+ const canvas = this.el.canvas;
304
+ canvas.removeEventListener('pointerdown', this._onPointerDown);
305
+ canvas.removeEventListener('pointermove', this._onPointerMove);
306
+ canvas.removeEventListener('pointerup', this._onPointerUp);
307
+ canvas.removeEventListener('pointercancel', this._onPointerUp);
308
+ canvas.removeEventListener('pointerleave', this._onPointerLeave);
309
+ canvas.removeEventListener('contextmenu', this._onContextMenu);
310
+
311
+ window.removeEventListener('pointerup', this._onPointerUp);
312
+ window.removeEventListener('blur', this._onWindowBlur);
313
+ window.removeEventListener('resize', this._onWindowResize);
314
+
315
+ this.toolButtons.forEach((btn) => btn.removeEventListener('click', this._onToolClick));
316
+ this.penTypeButtons.forEach((btn) => btn.removeEventListener('click', this._onPenTypeClick));
317
+ this.colorButtons.forEach((btn) => btn.removeEventListener('click', this._onColorClick));
318
+ this.backgroundButtons.forEach((btn) => btn.removeEventListener('click', this._onBackgroundClick));
319
+ this.el.customColor.removeEventListener('input', this._onCustomColorInput);
320
+ this.el.penSize.removeEventListener('input', this._onPenSizeInput);
321
+ this.el.eraserSize.removeEventListener('input', this._onEraserSizeInput);
322
+
323
+ this.strokes = [];
324
+ this.activeStroke = null;
325
+ this.root.remove();
326
+
327
+ if (this.transparentWindowApplied) {
328
+ document.documentElement.classList.remove('aboard-transparent-window');
329
+ this.transparentWindowApplied = false;
330
+ }
331
+ }
332
+
333
+ /* ---------- 设置存取 ---------- */
334
+
335
+ _loadSettings() {
336
+ const defaults = Object.assign({}, DEFAULTS);
337
+ if (!this.persist) return defaults;
338
+
339
+ try {
340
+ const raw = JSON.parse(localStorage.getItem(this.storageKey) || 'null');
341
+ if (!raw || typeof raw !== 'object') return defaults;
342
+
343
+ return {
344
+ tool: raw.tool === 'eraser' ? 'eraser' : 'pen',
345
+ penType: PEN_TYPES.indexOf(raw.penType) !== -1 ? raw.penType : defaults.penType,
346
+ color: HEX_COLOR.test(raw.color) ? String(raw.color).toLowerCase() : defaults.color,
347
+ penSize: clamp(Number(raw.penSize) || defaults.penSize, 1, 50),
348
+ eraserSize: clamp(Number(raw.eraserSize) || defaults.eraserSize, 10, 150),
349
+ background: raw.background === 'blackboard' ? 'blackboard' : 'transparent',
350
+ autoColor: raw.autoColor !== false
351
+ };
352
+ } catch (error) {
353
+ return defaults;
354
+ }
355
+ }
356
+
357
+ _saveSettings() {
358
+ if (!this.persist) return;
359
+
360
+ clearTimeout(this.saveTimer);
361
+ const settings = this.settings;
362
+ const storageKey = this.storageKey;
363
+ this.saveTimer = setTimeout(function () {
364
+ try {
365
+ localStorage.setItem(storageKey, JSON.stringify(settings));
366
+ } catch (error) {
367
+ /* 忽略隐私模式下的存储异常 */
368
+ }
369
+ }, 150);
370
+ }
371
+
372
+ _emitChange() {
373
+ if (this.onChange) this.onChange(this.getSettings());
374
+ }
375
+
376
+ _commit() {
377
+ this._syncUI();
378
+ this._saveSettings();
379
+ this._emitChange();
380
+ }
381
+
382
+ /* ---------- 公开 API ---------- */
383
+
384
+ getSettings() {
385
+ return Object.assign({}, this.settings);
386
+ }
387
+
388
+ getCanvas() {
389
+ return this.el.canvas;
390
+ }
391
+
392
+ getElement() {
393
+ return this.root;
394
+ }
395
+
396
+ setTool(tool) {
397
+ this.settings.tool = tool === 'eraser' ? 'eraser' : 'pen';
398
+ this._commit();
399
+ }
400
+
401
+ setPenType(penType) {
402
+ if (PEN_TYPES.indexOf(penType) === -1) return;
403
+ this.settings.penType = penType;
404
+ this._commit();
405
+ }
406
+
407
+ setColor(color) {
408
+ if (!HEX_COLOR.test(String(color))) return;
409
+ this.settings.color = String(color).toLowerCase();
410
+ this.settings.autoColor = false;
411
+ this._commit();
412
+ }
413
+
414
+ setPenSize(size) {
415
+ this.settings.penSize = clamp(Number(size) || DEFAULTS.penSize, 1, 50);
416
+ this._commit();
417
+ }
418
+
419
+ setEraserSize(size) {
420
+ this.settings.eraserSize = clamp(Number(size) || DEFAULTS.eraserSize, 10, 150);
421
+ if (this.settings.tool === 'eraser') {
422
+ this.el.eraserCursor.style.width = this.settings.eraserSize + 'px';
423
+ this.el.eraserCursor.style.height = this.settings.eraserSize + 'px';
424
+ }
425
+ this._commit();
426
+ }
427
+
428
+ setBackground(background) {
429
+ this._applyBackground(background);
430
+ }
431
+
432
+ setToolbarVisible(visible) {
433
+ this.el.toolbar.style.display = visible ? '' : 'none';
434
+ }
435
+
436
+ setBackgroundSwitcherVisible(visible) {
437
+ this.el.backgroundSwitcher.style.display = visible ? '' : 'none';
438
+ }
439
+
440
+ resize() {
441
+ this._resizeCanvas();
442
+ }
443
+
444
+ /* ---------- 画布尺寸 / 重绘 ---------- */
445
+
446
+ _resizeCanvas() {
447
+ if (this.destroyed) return;
448
+
449
+ const rect = this.el.surface.getBoundingClientRect();
450
+ const nextWidth = Math.max(1, Math.round(rect.width));
451
+ const nextHeight = Math.max(1, Math.round(rect.height));
452
+ const nextDpr = Math.min(window.devicePixelRatio || 1, MAX_DPR);
453
+
454
+ if (nextWidth === this.viewWidth && nextHeight === this.viewHeight && nextDpr === this.dpr) return;
455
+
456
+ this.viewWidth = nextWidth;
457
+ this.viewHeight = nextHeight;
458
+ this.dpr = nextDpr;
459
+
460
+ const canvas = this.el.canvas;
461
+ canvas.width = Math.round(this.viewWidth * this.dpr);
462
+ canvas.height = Math.round(this.viewHeight * this.dpr);
463
+ canvas.style.width = this.viewWidth + 'px';
464
+ canvas.style.height = this.viewHeight + 'px';
465
+
466
+ this.ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
467
+ this.ctx.imageSmoothingEnabled = true;
468
+ this._repaint();
469
+ }
470
+
471
+ _repaint() {
472
+ const ctx = this.ctx;
473
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
474
+ ctx.clearRect(0, 0, this.el.canvas.width, this.el.canvas.height);
475
+ ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0);
476
+
477
+ for (let i = 0; i < this.strokes.length; i += 1) {
478
+ this._renderStroke(this.strokes[i]);
479
+ }
480
+
481
+ ctx.globalCompositeOperation = 'source-over';
482
+ ctx.globalAlpha = 1;
483
+ ctx.setLineDash([]);
484
+ }
485
+
486
+ /* ---------- 绘制核心 ---------- */
487
+
488
+ _prepareContext(stroke) {
489
+ const ctx = this.ctx;
490
+ ctx.globalAlpha = 1;
491
+ ctx.setLineDash([]);
492
+
493
+ if (stroke.tool === 'eraser') {
494
+ // 只擦除绘图层,背景层(透明窗口即下层 PPT)不受影响
495
+ ctx.globalCompositeOperation = 'destination-out';
496
+ ctx.strokeStyle = '#000000';
497
+ ctx.fillStyle = '#000000';
498
+ ctx.lineWidth = stroke.size;
499
+ ctx.lineCap = 'round';
500
+ ctx.lineJoin = 'round';
501
+ return;
502
+ }
503
+
504
+ ctx.globalCompositeOperation = 'source-over';
505
+ ctx.strokeStyle = stroke.color;
506
+ ctx.fillStyle = stroke.color;
507
+ ctx.lineCap = 'round';
508
+ ctx.lineJoin = 'round';
509
+ ctx.globalAlpha = PEN_ALPHA[stroke.penType] || 1;
510
+ ctx.lineWidth = stroke.size * (PEN_WIDTH_FACTOR[stroke.penType] || 1);
511
+ }
512
+
513
+ _strokeLine(from, to) {
514
+ this.ctx.beginPath();
515
+ this.ctx.moveTo(from.x, from.y);
516
+ this.ctx.lineTo(to.x, to.y);
517
+ this.ctx.stroke();
518
+ }
519
+
520
+ _drawDot(point) {
521
+ const ctx = this.ctx;
522
+ const radius = Math.max(0.5, ctx.lineWidth / 2);
523
+ ctx.beginPath();
524
+ ctx.arc(point.x, point.y, radius, 0, Math.PI * 2);
525
+ ctx.fill();
526
+ }
527
+
528
+ _renderStroke(stroke) {
529
+ if (!stroke.points.length) return;
530
+
531
+ this._prepareContext(stroke);
532
+ this._drawDot(stroke.points[0]);
533
+
534
+ for (let i = 1; i < stroke.points.length; i += 1) {
535
+ this._drawSegment(stroke, stroke.points[i - 1], stroke.points[i]);
536
+ }
537
+ }
538
+
539
+ _drawSegment(stroke, from, to) {
540
+ const distance = Math.hypot(to.x - from.x, to.y - from.y);
541
+ if (distance === 0) return;
542
+
543
+ if (stroke.tool === 'eraser') {
544
+ this._strokeLine(from, to);
545
+ return;
546
+ }
547
+
548
+ switch (stroke.penType) {
549
+ case 'pencil':
550
+ this._drawPencilSegment(stroke, from, to);
551
+ break;
552
+ case 'ballpoint':
553
+ this._drawBallpointSegment(stroke, from, to, distance);
554
+ break;
555
+ case 'fountain':
556
+ this._drawFountainSegment(stroke, from, to, distance);
557
+ break;
558
+ case 'brush':
559
+ this._drawBrushSegment(stroke, from, to, distance);
560
+ break;
561
+ case 'marker':
562
+ this._drawMarkerSegment(stroke, from, to, distance);
563
+ break;
564
+ default:
565
+ this._strokeLine(from, to);
566
+ }
567
+ }
568
+
569
+ // 铅笔:低透明度主线 + 颗粒细线
570
+ _drawPencilSegment(stroke, from, to) {
571
+ const ctx = this.ctx;
572
+ const size = stroke.size;
573
+ const angle = Math.atan2(to.y - from.y, to.x - from.x);
574
+
575
+ ctx.save();
576
+ ctx.globalAlpha = 0.6;
577
+ ctx.lineWidth = size * 0.9;
578
+ this._strokeLine(from, to);
579
+
580
+ for (let i = 0; i < 2; i += 1) {
581
+ const seed = hashUnit(from.x, to.y, i * 43758.5453);
582
+ const offset = (seed - 0.5) * size * 0.3;
583
+ const perpX = Math.cos(angle + Math.PI / 2) * offset;
584
+ const perpY = Math.sin(angle + Math.PI / 2) * offset;
585
+
586
+ ctx.globalAlpha = 0.3 + seed * 0.2;
587
+ ctx.lineWidth = size * 0.4;
588
+ this._strokeLine(
589
+ { x: from.x + perpX, y: from.y + perpY },
590
+ { x: to.x + perpX, y: to.y + perpY }
591
+ );
592
+ }
593
+
594
+ ctx.restore();
595
+ }
596
+
597
+ // 圆珠笔:速度越快线越细
598
+ _drawBallpointSegment(stroke, from, to, distance) {
599
+ const ctx = this.ctx;
600
+ const size = stroke.size;
601
+ const minWidth = size * 0.7;
602
+ const maxWidth = size * 1.2;
603
+ const speedFactor = Math.min(distance / 8, 1);
604
+
605
+ ctx.save();
606
+ ctx.lineWidth = maxWidth - speedFactor * (maxWidth - minWidth);
607
+ ctx.globalAlpha = 0.95;
608
+ this._strokeLine(from, to);
609
+ ctx.restore();
610
+ }
611
+
612
+ // 钢笔:速度 + 方向共同影响笔宽
613
+ _drawFountainSegment(stroke, from, to, distance) {
614
+ const ctx = this.ctx;
615
+ const size = stroke.size;
616
+ const angle = Math.atan2(to.y - from.y, to.x - from.x);
617
+ const minWidth = size * 0.4;
618
+ const maxWidth = size * 1.8;
619
+ const speedFactor = Math.min(distance / 12, 1);
620
+ const directionFactor = Math.abs(Math.sin(angle * 2)) * 0.3;
621
+
622
+ ctx.save();
623
+ ctx.lineWidth = Math.max(minWidth, maxWidth - speedFactor * (maxWidth - minWidth) - directionFactor * size);
624
+ ctx.globalAlpha = 1;
625
+ this._strokeLine(from, to);
626
+ ctx.restore();
627
+ }
628
+
629
+ // 毛笔:宽笔触 + 毛边
630
+ _drawBrushSegment(stroke, from, to, distance) {
631
+ const ctx = this.ctx;
632
+ const size = stroke.size;
633
+ const angle = Math.atan2(to.y - from.y, to.x - from.x);
634
+ const speedFactor = Math.min(distance / 12, 1);
635
+ const brushWidth = size * 2 * (1 - speedFactor * 0.6);
636
+
637
+ ctx.save();
638
+ ctx.globalAlpha = 0.75;
639
+ ctx.lineWidth = brushWidth;
640
+ this._strokeLine(from, to);
641
+
642
+ for (let i = 0; i < 4; i += 1) {
643
+ const seed1 = hashUnit(from.x, to.y, i * 1.1);
644
+ const seed2 = hashUnit(from.y, to.x, i * 2.2);
645
+ const seed3 = hashUnit(to.x, from.y, i * 3.3);
646
+
647
+ const offset = (seed1 - 0.5) * brushWidth * 0.6;
648
+ const perpX = Math.cos(angle + Math.PI / 2) * offset;
649
+ const perpY = Math.sin(angle + Math.PI / 2) * offset;
650
+
651
+ ctx.globalAlpha = 0.1 + seed2 * 0.15;
652
+ ctx.lineWidth = brushWidth * (0.2 + seed3 * 0.4);
653
+ this._strokeLine(
654
+ { x: from.x + perpX, y: from.y + perpY },
655
+ { x: to.x + perpX, y: to.y + perpY }
656
+ );
657
+ }
658
+
659
+ ctx.restore();
660
+ }
661
+
662
+ // 荧光笔:半透明宽笔触
663
+ _drawMarkerSegment(stroke, from, to, distance) {
664
+ const ctx = this.ctx;
665
+ const size = stroke.size;
666
+ const minWidth = size * 1.6;
667
+ const maxWidth = size * 2.3;
668
+ const speedFactor = Math.min(distance / 15, 1);
669
+
670
+ ctx.save();
671
+ ctx.globalAlpha = 0.4;
672
+ ctx.lineWidth = maxWidth - speedFactor * (maxWidth - minWidth);
673
+ ctx.lineCap = 'square';
674
+ ctx.lineJoin = 'round';
675
+ this._strokeLine(from, to);
676
+ ctx.restore();
677
+ }
678
+
679
+ /* ---------- 坐标与指针 ---------- */
680
+
681
+ _getPoint(event) {
682
+ const rect = this.el.canvas.getBoundingClientRect();
683
+ return {
684
+ x: clamp(event.clientX - rect.left, 0, this.viewWidth),
685
+ y: clamp(event.clientY - rect.top, 0, this.viewHeight)
686
+ };
687
+ }
688
+
689
+ _startStroke(event) {
690
+ if (this.activePointerId !== null) return;
691
+ if (event.pointerType === 'mouse' && event.button !== 0) return;
692
+
693
+ const canvas = this.el.canvas;
694
+ this.activePointerId = event.pointerId;
695
+ try {
696
+ canvas.setPointerCapture(event.pointerId);
697
+ } catch (error) {
698
+ /* 部分环境不支持指针捕获 */
699
+ }
700
+
701
+ // 绘制期间隐藏配置面板与背景切换器,避免遮挡画布
702
+ this.root.classList.add('is-drawing');
703
+
704
+ const isEraser = this.settings.tool === 'eraser';
705
+ const point = this._getPoint(event);
706
+
707
+ this.activeStroke = {
708
+ tool: this.settings.tool,
709
+ penType: this.settings.penType,
710
+ color: this.settings.color,
711
+ size: isEraser ? this.settings.eraserSize : this.settings.penSize,
712
+ points: [point]
713
+ };
714
+
715
+ this._prepareContext(this.activeStroke);
716
+ this._drawDot(point);
717
+
718
+ event.preventDefault();
719
+ }
720
+
721
+ _appendPoint(point) {
722
+ if (!this.activeStroke) return;
723
+
724
+ const points = this.activeStroke.points;
725
+ const prev = points[points.length - 1];
726
+ if (!prev) return;
727
+
728
+ if (Math.abs(point.x - prev.x) < MIN_POINT_DISTANCE && Math.abs(point.y - prev.y) < MIN_POINT_DISTANCE) {
729
+ return;
730
+ }
731
+
732
+ points.push(point);
733
+ this._drawSegment(this.activeStroke, prev, point);
734
+ }
735
+
736
+ _onPointerMove = (event) => {
737
+ this._updateEraserCursor(event);
738
+
739
+ if (this.activePointerId === null || event.pointerId !== this.activePointerId || !this.activeStroke) return;
740
+
741
+ const coalesced = typeof event.getCoalescedEvents === 'function' ? event.getCoalescedEvents() : null;
742
+ const events = coalesced && coalesced.length ? coalesced : [event];
743
+
744
+ for (let i = 0; i < events.length; i += 1) {
745
+ this._appendPoint(this._getPoint(events[i]));
746
+ }
747
+
748
+ event.preventDefault();
749
+ };
750
+
751
+ _onPointerDown = (event) => {
752
+ this._startStroke(event);
753
+ };
754
+
755
+ _onPointerUp = (event) => {
756
+ this._finishStroke(event);
757
+ };
758
+
759
+ _onPointerLeave = () => {
760
+ if (this.activePointerId === null) this._hideEraserCursor();
761
+ };
762
+
763
+ _onContextMenu = (event) => {
764
+ event.preventDefault();
765
+ };
766
+
767
+ _onWindowBlur = () => {
768
+ this._finishStroke();
769
+ };
770
+
771
+ _onWindowResize = () => {
772
+ this._resizeCanvas();
773
+ };
774
+
775
+ _finishStroke(event) {
776
+ if (this.activePointerId === null) return;
777
+ if (event && event.pointerId !== undefined && event.pointerId !== this.activePointerId) return;
778
+
779
+ if (this.activeStroke && this.activeStroke.points.length) {
780
+ this.strokes.push(this.activeStroke);
781
+ }
782
+ this.activeStroke = null;
783
+
784
+ const pointerId = this.activePointerId;
785
+ this.activePointerId = null;
786
+
787
+ const canvas = this.el.canvas;
788
+ if (pointerId !== null && canvas.hasPointerCapture(pointerId)) {
789
+ try {
790
+ canvas.releasePointerCapture(pointerId);
791
+ } catch (error) {
792
+ /* 忽略释放失败 */
793
+ }
794
+ }
795
+
796
+ this.ctx.globalCompositeOperation = 'source-over';
797
+ this.ctx.globalAlpha = 1;
798
+ this.ctx.setLineDash([]);
799
+
800
+ this.root.classList.remove('is-drawing');
801
+ }
802
+
803
+ /* ---------- 橡皮擦光标 ---------- */
804
+
805
+ _updateEraserCursor(event) {
806
+ if (this.settings.tool !== 'eraser' || event.pointerType === 'touch') {
807
+ this._hideEraserCursor();
808
+ return;
809
+ }
810
+
811
+ const size = this.settings.eraserSize;
812
+ const cursor = this.el.eraserCursor;
813
+ cursor.style.width = size + 'px';
814
+ cursor.style.height = size + 'px';
815
+ cursor.style.left = event.clientX + 'px';
816
+ cursor.style.top = event.clientY + 'px';
817
+ cursor.style.display = 'block';
818
+ }
819
+
820
+ _hideEraserCursor() {
821
+ this.el.eraserCursor.style.display = 'none';
822
+ }
823
+
824
+ /* ---------- 界面同步 ---------- */
825
+
826
+ _syncUI() {
827
+ const settings = this.settings;
828
+ const isEraser = settings.tool === 'eraser';
829
+
830
+ this.toolButtons.forEach(function (btn) {
831
+ const active = btn.dataset.tool === settings.tool;
832
+ btn.classList.toggle('is-active', active);
833
+ btn.setAttribute('aria-pressed', active ? 'true' : 'false');
834
+ });
835
+
836
+ this.el.penConfig.classList.toggle('is-active', !isEraser);
837
+ this.el.eraserConfig.classList.toggle('is-active', isEraser);
838
+ this.el.canvas.classList.toggle('is-eraser', isEraser);
839
+
840
+ if (!isEraser) this._hideEraserCursor();
841
+
842
+ this.penTypeButtons.forEach(function (btn) {
843
+ const active = btn.dataset.penType === settings.penType;
844
+ btn.classList.toggle('is-active', active);
845
+ btn.setAttribute('aria-pressed', active ? 'true' : 'false');
846
+ });
847
+
848
+ this.colorButtons.forEach(function (btn) {
849
+ const active = btn.dataset.color.toLowerCase() === settings.color;
850
+ btn.classList.toggle('is-active', active);
851
+ btn.setAttribute('aria-pressed', active ? 'true' : 'false');
852
+ });
853
+
854
+ this.el.customColor.value = settings.color;
855
+ this.el.penSize.value = String(settings.penSize);
856
+ this.el.penSizeValue.textContent = String(settings.penSize);
857
+ this.el.eraserSize.value = String(settings.eraserSize);
858
+ this.el.eraserSizeValue.textContent = String(settings.eraserSize);
859
+
860
+ this.backgroundButtons.forEach(function (btn) {
861
+ const active = btn.dataset.background === settings.background;
862
+ btn.classList.toggle('is-active', active);
863
+ btn.setAttribute('aria-pressed', active ? 'true' : 'false');
864
+ });
865
+
866
+ this.root.dataset.background = settings.background;
867
+
868
+ if (isEraser) {
869
+ this.el.eraserCursor.style.width = settings.eraserSize + 'px';
870
+ this.el.eraserCursor.style.height = settings.eraserSize + 'px';
871
+ }
872
+ }
873
+
874
+ _applyBackground(background, options) {
875
+ const opts = options || {};
876
+ const next = background === 'transparent' ? 'transparent' : 'blackboard';
877
+ const previous = this.settings.background;
878
+
879
+ this.settings.background = next;
880
+
881
+ const isTransparent = next === 'transparent';
882
+ this.el.surface.classList.toggle('bg-transparent', isTransparent);
883
+ this.el.surface.classList.toggle('bg-blackboard', !isTransparent);
884
+
885
+ // 用户没有手动选过颜色时,根据背景自动切换黑白,避免新笔迹不可见
886
+ if (opts.autoSwapColor !== false && this.settings.autoColor && previous !== next) {
887
+ if (isTransparent && this.settings.color === COLOR_ON_BLACKBOARD) {
888
+ this.settings.color = COLOR_ON_TRANSPARENT;
889
+ } else if (!isTransparent && this.settings.color === COLOR_ON_TRANSPARENT) {
890
+ this.settings.color = COLOR_ON_BLACKBOARD;
891
+ }
892
+ }
893
+
894
+ if (opts.sync !== false) this._syncUI();
895
+ if (opts.persist !== false) this._saveSettings();
896
+ if (opts.sync !== false) this._emitChange();
897
+ }
898
+
899
+ /* ---------- 事件绑定 ---------- */
900
+
901
+ _bindEvents() {
902
+ const canvas = this.el.canvas;
903
+
904
+ canvas.addEventListener('pointerdown', this._onPointerDown);
905
+ canvas.addEventListener('pointermove', this._onPointerMove);
906
+ canvas.addEventListener('pointerup', this._onPointerUp);
907
+ canvas.addEventListener('pointercancel', this._onPointerUp);
908
+ canvas.addEventListener('pointerleave', this._onPointerLeave);
909
+ canvas.addEventListener('contextmenu', this._onContextMenu);
910
+
911
+ window.addEventListener('pointerup', this._onPointerUp);
912
+ window.addEventListener('blur', this._onWindowBlur);
913
+ window.addEventListener('resize', this._onWindowResize);
914
+
915
+ this.toolButtons.forEach((btn) => btn.addEventListener('click', this._onToolClick));
916
+ this.penTypeButtons.forEach((btn) => btn.addEventListener('click', this._onPenTypeClick));
917
+ this.colorButtons.forEach((btn) => btn.addEventListener('click', this._onColorClick));
918
+ this.backgroundButtons.forEach((btn) => btn.addEventListener('click', this._onBackgroundClick));
919
+ this.el.customColor.addEventListener('input', this._onCustomColorInput);
920
+ this.el.penSize.addEventListener('input', this._onPenSizeInput);
921
+ this.el.eraserSize.addEventListener('input', this._onEraserSizeInput);
922
+
923
+ if (typeof ResizeObserver === 'function') {
924
+ this.resizeObserver = new ResizeObserver(this._onWindowResize);
925
+ this.resizeObserver.observe(this.el.surface);
926
+ }
927
+ }
928
+
929
+ _onToolClick = (event) => {
930
+ this.setTool(event.currentTarget.dataset.tool);
931
+ };
932
+
933
+ _onPenTypeClick = (event) => {
934
+ this.setPenType(event.currentTarget.dataset.penType);
935
+ };
936
+
937
+ _onColorClick = (event) => {
938
+ this.setColor(event.currentTarget.dataset.color);
939
+ };
940
+
941
+ _onCustomColorInput = (event) => {
942
+ this.setColor(event.target.value);
943
+ };
944
+
945
+ _onPenSizeInput = (event) => {
946
+ this.setPenSize(event.target.value);
947
+ };
948
+
949
+ _onEraserSizeInput = (event) => {
950
+ this.setEraserSize(event.target.value);
951
+ };
952
+
953
+ _onBackgroundClick = (event) => {
954
+ this.setBackground(event.currentTarget.dataset.background);
955
+ };
956
+ }
957
+
958
+ function hashUnit(x, y, i) {
959
+ const h = Math.sin(x * 12.9898 + y * 78.233 + i * 43758.5453) * 43758.5453;
960
+ return h - Math.floor(h);
961
+ }
962
+
963
+ export default Aboard;