-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
644 lines (532 loc) · 19.3 KB
/
Copy pathscript.js
File metadata and controls
644 lines (532 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
// 应用状态
const appState = {
currentImageSize: { width: 64, height: 64 },
isDrawing: false,
currentCanvas: null,
imageGallery: [],
cellSize: 0,
brushSize: 1, // 画笔粗细
lastMousePos: null // 上一次鼠标位置
};
// 本地存储键名
const STORAGE_KEY = 'dtd-workspace';
// 初始化函数
function init() {
// 加载本地存储数据
loadFromStorage();
//初始化尺寸选择框
initSizeSelect();
// 初始化Canvas
initCanvas();
// 绑定事件监听器
bindEventListeners();
// 渲染图片夹
renderGallery();
}
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);
// 防止页面缩放和滚动影响绘图体验
document.addEventListener('touchmove', function(e) {
// 只在触摸发生在Canvas上时防止默认行为
if (e.target === document.getElementById('drawingCanvas')) {
e.preventDefault();
}
}, { passive: false });
//初始化尺寸选择框
function initSizeSelect() {
const sizeSelect = document.getElementById('sizeSelect');
const customSize = document.getElementById('customSize');
const widthInput = document.getElementById('widthInput');
const heightInput = document.getElementById('heightInput');
const { width, height } = appState.currentImageSize;
if(width === height){
if(width === 16 || width === 32 || width === 64 || width === 128){
sizeSelect.value = appState.currentImageSize.height+"x"+appState.currentImageSize.width;
return;
}
}
customSize.style.display = 'inline-block';
sizeSelect.value = "custom";
widthInput.value = width;
heightInput.value = height;
}
// Canvas初始化
function initCanvas() {
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
// 设置Canvas大小,根据屏幕尺寸动态调整
const maxCanvasSize = Math.min(
window.innerWidth * 0.93,
window.innerHeight * 0.87,
600
);
const { width, height } = appState.currentImageSize;
// console.log("width:",width,",height:",height)
// 计算单元格大小
appState.cellSize = Math.min(
Math.floor(maxCanvasSize / width),
Math.floor(maxCanvasSize / height)
);
// 设置Canvas实际尺寸
canvas.width = width * appState.cellSize;
canvas.height = height * appState.cellSize;
// 绘制网格
drawGrid(ctx);
// 初始化空白图像数据
appState.currentCanvas = createEmptyCanvas(width, height);
}
// 窗口大小改变时重新调整Canvas
window.addEventListener('resize', function() {
initCanvas();
});
// 事件监听器绑定
function bindEventListeners() {
// 尺寸选择事件
document.getElementById('sizeSelect').addEventListener('change', handleSizeChange);
document.getElementById('applySizeBtn').addEventListener('click', applyCustomSize);
// Canvas事件
const canvas = document.getElementById('drawingCanvas');
canvas.addEventListener('mousedown', handleMouseDown);
canvas.addEventListener('mousemove', handleMouseMove);
canvas.addEventListener('mouseup', handleMouseUp);
canvas.addEventListener('mouseleave', handleMouseUp);
// 触摸事件支持
canvas.addEventListener('touchstart', handleTouchStart);
canvas.addEventListener('touchmove', handleTouchMove);
canvas.addEventListener('touchend', handleTouchEnd);
canvas.addEventListener('touchcancel', handleTouchEnd);
// 控制按钮事件
document.getElementById('saveBtn').addEventListener('click', saveToGallery);
document.getElementById('resetBtn').addEventListener('click', resetCanvas);
document.getElementById('clearGalleryBtn').addEventListener('click', clearGallery);
// 导出事件
document.getElementById('exportBtn').addEventListener('click', exportDataset);
// 画笔设置事件
document.getElementById('brushSize').addEventListener('input', handleBrushSizeChange);
// 导出格式切换事件
const exportFormats = document.querySelectorAll('input[name="exportFormat"]');
exportFormats.forEach(format => {
format.addEventListener('change', handleExportFormatChange);
});
}
// 尺寸选择事件处理
function handleSizeChange() {
const sizeSelect = document.getElementById('sizeSelect');
const customSize = document.getElementById('customSize');
if (sizeSelect.value === 'custom') {
customSize.style.display = 'inline-block';
} else {
customSize.style.display = 'none';
// 应用预设尺寸
const [width, height] = sizeSelect.value.split('x').map(Number);
applyNewSize(width, height);
}
}
// 应用自定义尺寸
function applyCustomSize() {
const widthInput = document.getElementById('widthInput');
const heightInput = document.getElementById('heightInput');
const width = parseInt(widthInput.value);
const height = parseInt(heightInput.value);
if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0) {
alert('请输入有效的宽高值');
return;
}
applyNewSize(width, height);
}
// 应用新尺寸
function applyNewSize(width, height) {
// 如果图片夹有图片,弹出确认提示
if (appState.imageGallery.length > 0) {
if (!confirm('中途更改图片大小会清空图片夹,是否继续?')) {
// 恢复原来的选择
const sizeSelect = document.getElementById('sizeSelect');
sizeSelect.value = `${appState.currentImageSize.width}x${appState.currentImageSize.height}`;
// 显示/隐藏自定义尺寸输入框
const customSize = document.getElementById('customSize');
customSize.style.display = sizeSelect.value === 'custom' ? 'inline-block' : 'none';
return;
}
// 清空图片夹
appState.imageGallery = [];
saveToStorage();
renderGallery();
}
// 更新尺寸并重新初始化Canvas
appState.currentImageSize = { width, height };
initCanvas();
resetCanvas();
saveToStorage();
}
// 鼠标事件处理
// 画笔大小调整事件处理
function handleBrushSizeChange() {
appState.brushSize = parseInt(document.getElementById('brushSize').value);
document.getElementById('brushSizeValue').textContent = appState.brushSize;
}
// 导出格式切换事件处理
function handleExportFormatChange() {
const selectedFormat = document.querySelector('input[name="exportFormat"]:checked').value;
const txtExportOptions = document.getElementById('txtExportOptions');
txtExportOptions.style.display = selectedFormat === 'txt' ? 'block' : 'none';
}
// Canvas事件处理
function handleMouseDown(e) {
appState.isDrawing = true;
const rect = document.getElementById('drawingCanvas').getBoundingClientRect();
appState.lastMousePos = {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
appState.lastMouseTime = Date.now();
drawCell(e);
}
function handleMouseMove(e) {
if (appState.isDrawing) {
drawCell(e);
}
}
function handleMouseUp() {
appState.isDrawing = false;
appState.lastMousePos = null;
}
// 触摸事件处理函数
function handleTouchStart(e) {
// 防止默认触摸行为(如缩放、滚动)
e.preventDefault();
appState.isDrawing = true;
const rect = document.getElementById('drawingCanvas').getBoundingClientRect();
const touch = e.touches[0];
// 直接使用触摸坐标,不创建模拟事件
const currentMousePos = {
x: touch.clientX - rect.left,
y: touch.clientY - rect.top
};
appState.lastMousePos = currentMousePos;
// 如果有上一次的鼠标位置,绘制当前位置和上一次位置之间的连线
if (appState.lastMousePos) {
drawLine(appState.lastMousePos, currentMousePos);
} else {
// 否则只绘制当前位置
drawCircle(currentMousePos, appState.brushSize);
}
}
function handleTouchMove(e) {
// 防止默认触摸行为(如缩放、滚动)
e.preventDefault();
if (appState.isDrawing) {
const rect = document.getElementById('drawingCanvas').getBoundingClientRect();
const touch = e.touches[0];
// 直接使用触摸坐标,不创建模拟事件
const currentMousePos = {
x: touch.clientX - rect.left,
y: touch.clientY - rect.top
};
// 如果有上一次的鼠标位置,绘制当前位置和上一次位置之间的连线
if (appState.lastMousePos) {
drawLine(appState.lastMousePos, currentMousePos);
} else {
// 否则只绘制当前位置
drawCircle(currentMousePos, appState.brushSize);
}
// 更新上一次鼠标位置
appState.lastMousePos = currentMousePos;
}
}
function handleTouchEnd(e) {
e.preventDefault();
appState.isDrawing = false;
appState.lastMousePos = null;
}
// 绘制单元格
function drawCell(e) {
const canvas = document.getElementById('drawingCanvas');
const rect = canvas.getBoundingClientRect();
const currentMousePos = {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
// 如果有上一次的鼠标位置,绘制当前位置和上一次位置之间的连线
if (appState.lastMousePos) {
drawLine(appState.lastMousePos, currentMousePos);
} else {
// 否则只绘制当前位置
drawCircle(currentMousePos, appState.brushSize);
}
// 更新上一次鼠标位置
appState.lastMousePos = currentMousePos;
}
function drawLine(startPos, endPos) {
const dx = endPos.x - startPos.x;
const dy = endPos.y - startPos.y;
const distance = Math.hypot(dx, dy);
const step = Math.max(1, Math.floor(appState.brushSize / 2));
const steps = Math.ceil(distance / step);
for (let i = 0; i <= steps; i++) {
const t = i / steps;
const x = startPos.x + dx * t;
const y = startPos.y + dy * t;
drawCircle({ x, y }, appState.brushSize);
}
}
// 绘制圆形区域
function drawCircle(pos, brushSize) {
// 计算对应的网格坐标
const gridX = Math.floor(pos.x / appState.cellSize);
const gridY = Math.floor(pos.y / appState.cellSize);
// 绘制圆形区域
const radius = brushSize / 2;
// 计算需要绘制的网格范围
const minX = Math.max(0, Math.floor(gridX - radius));
const maxX = Math.min(appState.currentImageSize.width - 1, Math.ceil(gridX + radius));
const minY = Math.max(0, Math.floor(gridY - radius));
const maxY = Math.min(appState.currentImageSize.height - 1, Math.ceil(gridY + radius));
for (let y = minY; y <= maxY; y++) {
for (let x = minX; x <= maxX; x++) {
// 计算该网格点到圆心的距离
const distance = Math.sqrt(Math.pow(x - gridX, 2) + Math.pow(y - gridY, 2));
// 如果距离小于等于半径,则填充该网格点
if (distance <= radius) {
appState.currentCanvas[y][x] = 1; // 1表示黑色
drawSingleCell(x, y);
}
}
}
}
// 保存到图片夹
function saveToGallery() {
// 深拷贝当前Canvas数据
const imageData = JSON.parse(JSON.stringify(appState.currentCanvas));
// 添加到图片夹
appState.imageGallery.push({
id: `img_${Date.now()}`,
data: imageData,
width: appState.currentImageSize.width,
height: appState.currentImageSize.height,
createdAt: new Date().toISOString()
});
// 保存到本地存储
saveToStorage();
// 渲染图片夹
renderGallery();
// 重置当前Canvas
resetCanvas();
}
// 重置画板
function resetCanvas() {
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
// 清除Canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 重新绘制网格
drawGrid(ctx);
// 重新初始化空白图像数据
const { width, height } = appState.currentImageSize;
appState.currentCanvas = createEmptyCanvas(width, height);
}
// 清空图片夹
function clearGallery() {
if (appState.imageGallery.length === 0) {
alert('图片夹已经是空的');
return;
}
if (confirm('确定要清空图片夹吗?')) {
appState.imageGallery = [];
saveToStorage();
renderGallery();
}
}
// 渲染图片夹
function renderGallery() {
const container = document.getElementById('galleryContainer');
const count = document.getElementById('imageCount');
// 更新图片数量
count.textContent = appState.imageGallery.length;
// 清空容器
container.innerHTML = '';
// 渲染每个图片
appState.imageGallery.forEach((image, index) => {
const item = document.createElement('div');
item.className = 'gallery-item';
// 创建缩略图画布
const thumbCanvas = document.createElement('canvas');
thumbCanvas.width = 60;
thumbCanvas.height = 60;
const thumbCtx = thumbCanvas.getContext('2d');
// 绘制缩略图
const thumbCellSize = Math.min(thumbCanvas.width / image.width, thumbCanvas.height / image.height);
image.data.forEach((row, y) => {
row.forEach((cell, x) => {
if (cell === 1) {
thumbCtx.fillStyle = 'black';
thumbCtx.fillRect(
x * thumbCellSize,
y * thumbCellSize,
thumbCellSize,
thumbCellSize
);
}
});
});
// 创建容器用于包裹画布和删除按钮
const canvasContainer = document.createElement('div');
canvasContainer.className = 'canvas-container';
// 添加缩略图画布
canvasContainer.appendChild(thumbCanvas);
// 添加新的删除按钮(垃圾桶图标)
const deleteBtn = document.createElement('button');
deleteBtn.className = 'trash-btn';
deleteBtn.innerHTML = '🗑️'; // 垃圾桶图标
deleteBtn.title = '删除图片';
deleteBtn.onclick = () => deleteFromGallery(index);
canvasContainer.appendChild(deleteBtn);
item.appendChild(canvasContainer);
container.appendChild(item);
});
}
// 从图片夹中删除图片
function deleteFromGallery(index) {
if (confirm('确定要删除这张图片吗?')) {
// 从数组中删除指定索引的图片
appState.imageGallery.splice(index, 1);
// 保存到本地存储
saveToStorage();
// 重新渲染图片夹
renderGallery();
}
}
// 本地存储实现
function saveToStorage() {
console.log("saveToStorage");
const data = {
imageGallery: appState.imageGallery,
currentImageSize: appState.currentImageSize,
lastModified: new Date().toISOString()
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}
function loadFromStorage() {
const storedData = localStorage.getItem(STORAGE_KEY);
if (storedData) {
const data = JSON.parse(storedData);
appState.imageGallery = data.imageGallery || [];
console.log("currentImageSize:",data.currentImageSize)
appState.currentImageSize = data.currentImageSize || { width: 32, height: 32 };
}
}
// 导出数据集
async function exportDataset() {
const format = document.querySelector('input[name="exportFormat"]:checked').value;
const zip = new JSZip();
if (appState.imageGallery.length === 0) {
alert('图片夹为空,请先绘制图片!');
return;
}
if (format === 'bmp') {
// 导出为BMP
for (let i = 0; i < appState.imageGallery.length; i++) {
const image = appState.imageGallery[i];
const bmpData = await convertToBMP(image);
zip.file(`image_${i}.bmp`, bmpData);
}
} else {
// 导出为TXT
const txtExportType = document.querySelector('input[name="txtExportType"]:checked').value;
if (txtExportType === 'multiple') {
// 保存为多个TXT文件
for (let i = 0; i < appState.imageGallery.length; i++) {
const image = appState.imageGallery[i];
const txtContent = JSON.stringify(image.data);
zip.file(`image_${i}.txt`, txtContent);
}
} else {
// 保存为一个TXT文件,使用三维数组
const allImagesData = [];
for (const image of appState.imageGallery) {
allImagesData.push(image.data);
}
const txtContent = JSON.stringify(allImagesData);
zip.file('dataset.txt', txtContent);
}
}
// 生成ZIP文件并下载
const zipContent = await zip.generateAsync({ type: 'blob' });
const timestamp = new Date().getTime();
saveAs(zipContent, `dtd-dataset-${timestamp}.zip`);
}
// 辅助函数
// 创建空白画布数据
function createEmptyCanvas(width, height) {
const canvas = [];
for (let y = 0; y < height; y++) {
canvas[y] = [];
for (let x = 0; x < width; x++) {
canvas[y][x] = 0; // 0表示白色
}
}
return canvas;
}
// 绘制网格
function drawGrid(ctx) {
const { width, height } = appState.currentImageSize;
const cellSize = appState.cellSize;
ctx.strokeStyle = '#eee';
ctx.lineWidth = 0.5;
// 绘制垂直线
for (let x = 0; x <= width; x++) {
ctx.beginPath();
ctx.moveTo(x * cellSize, 0);
ctx.lineTo(x * cellSize, height * cellSize);
ctx.stroke();
}
// 绘制水平线
for (let y = 0; y <= height; y++) {
ctx.beginPath();
ctx.moveTo(0, y * cellSize);
ctx.lineTo(width * cellSize, y * cellSize);
ctx.stroke();
}
}
// 绘制单个单元格
function drawSingleCell(x, y) {
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(
x * appState.cellSize,
y * appState.cellSize,
appState.cellSize,
appState.cellSize
);
// 重绘单元格边框
ctx.strokeStyle = '#eee';
ctx.lineWidth = 0.5;
ctx.strokeRect(
x * appState.cellSize,
y * appState.cellSize,
appState.cellSize,
appState.cellSize
);
}
// 转换为BMP格式
async function convertToBMP(image) {
// 创建临时Canvas
const tempCanvas = document.createElement('canvas');
tempCanvas.width = image.width;
tempCanvas.height = image.height;
const tempCtx = tempCanvas.getContext('2d');
// 绘制像素
for (let y = 0; y < image.height; y++) {
for (let x = 0; x < image.width; x++) {
const color = image.data[y][x] === 1 ? '#000000' : '#FFFFFF';
tempCtx.fillStyle = color;
tempCtx.fillRect(x, y, 1, 1);
}
}
// 转换为BMP
return new Promise((resolve) => {
tempCanvas.toBlob((blob) => {
resolve(blob);
}, 'image/bmp');
});
}