-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.html
1476 lines (1333 loc) · 66.8 KB
/
index.html
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拼豆辅助工具</title>
<link rel="shortcut icon" href="/image/favicon.png" type="image/png">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
body {
margin: 0;
overflow-x: hidden;
}
canvas {
border: 1px solid #060606;
}
#mainContent {
display: none;
}
.colorBlock {
display: inline-block;
width: 24px;
height: 24px;
text-align: center;
line-height: 24px;
margin: 2px;
vertical-align: top;
font: 11px monospace;
border: 1px solid #060606;
}
.pointer {
cursor: pointer;
}
.colorBlock.selected {
border: 3px solid #ff0000;
}
td {
text-align: center;
vertical-align: middle;
}
.mask {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
a:hover {
text-decoration: none;
}
</style>
<script src="js/palette.v2.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.4.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src='https://ajax.aspnetcdn.com/ajax/bootstrap/4.3.1/bootstrap.min.js'></script>
</head>
<body>
<div class="card">
<div class="h3 card-header">
<label>拼豆辅助工具</label>
<div class="float-right mx-2" class='align-top'>
<img src='image/help.png' style='height: 2rem;' data-toggle="modal" data-target="#docModal"
title="帮助文档" />
<span class="h6">中文/<a href="/index-en.html">Eng</a></span>
</div>
</div>
<div class="card-body">
<form>
<div class="form-group">
<div class="row">
<label class="col-sm-2 col-form-label">选择图片:</label>
<div class="custom-file col-sm-4">
<input type="file" class="custom-file-input" id="imageChooser"
accept="image/png, image/jpeg, image/gif" />
<label class="custom-file-label" for="imageChooser"></label>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-sm-2 col-form-label">拼豆品牌:</label>
<select id="paletteSelect" class="form-control col-sm-4">
<option value="mard" selected>Mard融合豆</option>
<option value="hama">Hama</option>
<option value="perler">Perler 5mm</option>
<option value="perler-mini">Perler mini 2.6mm</option>
<option value="nabbi">Nabbi</option>
<option value="artkal-s">Artkal S 5mm</option>
<option value="artkal-r">Artkal R soft 5mm</option>
<option value="artkal-c">Artkal C 2.6mm</option>
<option value="artkal-a">Artkal A soft 2.6mm</option>
</select>
</div>
</div>
<div class="form-group">
<div class="row">
<label class="col-sm-2 col-form-label">图块大小:</label>
<select id="pieceSizeSelect" class="form-control col-sm-4">
<option value="20">20x20</option>
<option value="25">25x25</option>
<option value="30">30x30</option>
<option value="40" selected>40x40</option>
<option value="50">50x50</option>
</select>
</div>
</div>
</form>
</div>
</div>
<div id='mainContent'>
<div class="row">
<div class="col">
<div class="card">
<div class="card-header">
原始图片
</div>
<div class="card-body">
<canvas id="originalCanvas"></canvas>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-header">
完整图片
</div>
<div class="card-body">
<canvas id="fullCanvas"></canvas>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-header">
图片切块
</div>
<div class="card-body">
<table id='sliceImageContainer' class='table-bordered'>
</table>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<label id='largePicInfo' class="col-form-label"></label>
<div class="dropdown float-right mx-2">
<button class="btn btn-outline-danger dropdown-toggle" type="button" id="dropdownColorReplace"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
颜色替换
</button>
<div class="dropdown-menu dropdown-menu-right overflow-auto" aria-labelledby="dropdownColorReplace"
style="max-height:800px;">
<div class="px-4 py-3">
<button type="button" class="btn btn-danger btn-sm" id="removeAllColorReplace">全部删除</button>
<button type="button" class="btn btn-primary btn-sm"
id="showColorReplaceJsonModel">导入/导出</button>
<div class="dropdown-divider"></div>
<h6 class="dropdown-header">全体颜色替换列表</h6>
<table class="table table-sm" style="max-width: 180px;">
<thead>
<th style="width: 36px;">旧</th>
<th style="width: 36px;">新</th>
<th></th>
</thead>
<tbody id="colorReplaceTable">
</tbody>
</table>
<h6 class="dropdown-header">单个像素颜色替换列表</h6>
<table class="table table-sm" style="min-width: 220px;">
<thead>
<th>坐标</th>
<th style="width: 36px;">旧</th>
<th style="width: 36px;">新</th>
<th></th>
</thead>
<tbody id="pixelColorReplaceTable">
</tbody>
</table>
</div>
</div>
</div>
<div class="dropdown float-right mx-2">
<button class="btn btn-outline-primary dropdown-toggle" type="button" id="dropdownColorSum"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
颜色统计
</button>
<div class="dropdown-menu dropdown-menu-right overflow-auto" aria-labelledby="dropdownColorSum"
id="colorSum" style="max-height:600px;min-width: 180px;">
<table class="table table-sm">
<thead>
<th style="width: 36px;">颜色</th>
<th>数量</th>
<th></th>
</thead>
<tbody id="colorSumTable">
</tbody>
</table>
</div>
</div>
<div class="float-right mx-2" id="brushToolBar">
<label id='brushInfo'></label>
<button type="button" class="btn btn-danger" id="disableBrushMode">退出</button>
</div>
</div>
<div class="card-body" style='padding: 0;'>
<canvas id="viewCanvas"></canvas>
</div>
</div>
</div>
<div class="modal fade" id="colorModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" id="pointDialogTitle"></h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div>
<div id="colorInfo"> </div>
<hr />
<button type="button" class="btn btn-primary" id='showSingleColor'>只显示此颜色</button>
<hr />
<strong>颜色替换:</strong>
<div id="colorSelector">
</div>
<div id='colorToolBar' class='row justify-content-around py-3'>
<button type="button" class="btn btn-primary" id='replaceColor'>替换所有颜色</button>
<button type="button" class="btn btn-primary" id='replacePixel'>只替换此像素点</button>
<button type="button" class="btn btn-info" id='replacePixelBrush'>进入笔刷模式</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="colorReplaceJsonModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">导入/导出颜色替换配置</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<label>颜色替换配置:</label>
<textarea class="form-control" rows="10" id="colorReplaceJson"></textarea>
<div id="copySuccessAlert" class="alert alert-success">
<a href="#" class="close" data-dismiss="alert">×</a>
复制成功!
</div>
<div id="importErrorAlert" class="alert alert-warning">
<a href="#" class="close" data-dismiss="alert">×</a>
导入格式错误!
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-primary" id="copyColorReplaceJson">复制到剪贴板</button>
<button type="button" class="btn btn-primary" id="importColorReplaceJson">导入</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="docModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">使用说明</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>本程序为辅助拼豆(Fuse Bead)的制作而开发的辅助工具。以网页形式运行,基于HTML5+JS。</p>
<p class="text-success">隐私声明:所有图形处理工作都在浏览器本地进行,不会上传或保存您的图片。</p>
<p>操作指南: </p>
<p>
<ul>
<li>可以上传本地图片,将每个像素转换成为相近颜色的拼豆并放大,供实际拼豆时参考;</li>
<li>图片限制尺寸为500x500,建议使用PNG格式;</li>
<li>可以将图片切分成不同尺寸的图块,点击上方图块或全图可以切换放大部分;</li>
<li>大图上方的“颜色统计”按钮可以查看所有颜色的拼豆数量;</li>
<li>可以只显示某种颜色用于快速摆放拼豆,一种方式是点击大图上的像素在弹出对话框中操作,另一种是在颜色统计按钮中直接点击颜色旁边的<<按钮;</li>
<li>点击大图上的像素,可以在弹出对话框中选择替换颜色,有三种方法:
<ul>
<li>替换所有颜色为另一种颜色; </li>
<li>替换当前像素为另一种颜色; </li>
<li>使用笔刷模式在大图上批量修改颜色;</li>
</ul>
</li>
<li>大图上方的“颜色替换”按钮可以查看并删除所有已替换的颜色,也可以导入/导出所有替换列表,方便制作大型拼豆项目。</li>
</ul>
</p>
<p>当前的拼豆调色板默认为<b>Mard</b>品牌的融合豆,并增加了国外几个较主流品牌的颜色作为参考。</p>
<p>调色板引用自:<a
href="https://www.reddit.com/r/beadsprites/comments/7ebgal/xml_files_of_all_the_colors_hama_perler_nabbi/"
target="_blank" class="text-secondary">Reddit原帖</a></p>
<p class="text-info">最后更新时间:2020.1.9</p class="text-info">
<p class="text-right">
by <a href="https://www.zhihu.com/people/aton" target="_blank"> 苏莉安 </a>
<a href="https://github.com/atonasting/fuse-bead-tool" target="_blank">
<img src='image/GitHub-Mark-64px.png' style='height: 2rem;' title="访问Github查看最新源代码" />
</a>
</p>
</div>
</div>
</div>
</div>
<div class="modal hide" id="loadingMask" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"
data-keyboard="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="mask">
<div class="spinner-border text-dark m-3" role="status">
<span class="sr-only"></span>
</div>
<span class="h1"> 绘制中...</span>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
const pixelSize = 20,//马赛克像素尺寸(放大倍数)
dragMinTimeSpan = 20,//拖拽所需的鼠标按下最小时间间隔(ms)
dragMinDistance = 8,//拖拽所需的鼠标移动最小距离(像素)
imageSizeLimit = 500;//图片尺寸大小限制
var pieceSize = 40;//单块拼板容纳的拼豆数
var paletteMap = generatePaletteMap(allPalettes.get("mard")),//调色板对象
similarColorCache = new Map(),//与实际颜色最相近的调色板颜色缓存
paletteImageData = new Array(),//存储原始图片替换调色板颜色后的原图
sliceImages = new Array(),//存储所有切块图的二维数组
currentSliceImage = null;//当前显示的切块图位置(显示全图时为null)
var selectedPixel = null,//当前选中的像素点(x,y,color)
filterColor = '',//颜色筛选(只显示此颜色的色块)
colorReplaceList = new Map(),//颜色替换列表
pixelColorReplaceList = new Map();//颜色替换列表(单个像素)
var isMouseDown = false,
mousedownStartTime = null,//鼠标按下的时间
mousedownStartX = 0,//鼠标按下的起点X
mousedownStartY = 0,//鼠标按下的起点Y
isDragging = false,//视图是否正在拖拽中
isBrushMode = false,//是否处于笔刷模式(点击大图直接换色)
brushColor = '';//笔刷颜色
var largeCanvas,//生成的马赛克大图Canvas,切出一部分显示在ViewCanvas
largeCanvasStartOffsetX = 0,//拖拽开始时的背景X坐标偏移
largeCanvasStartOffsetY = 0,//拖拽开始时的背景Y坐标偏移
largeCanvasOffsetX = 0,//背景大图的X坐标偏移
largeCanvasOffsetY = 0,//背景大图的Y坐标偏移
isDrawingViewCanvas = false,//视图是否正在绘制中
colorSum = new Map();//大图颜色统计
var scrollbarWidth = getScrollbarWidth();
var rulerX1Canvas, rulerX2Canvas, rulerY1Canvas, rulerY2Canvas;//四个标尺的canvas
$().ready(function () {
var originalCanvas = document.getElementById('originalCanvas'),//原始图片canvas
fullCanvas = document.getElementById('fullCanvas'),//完整图片canvas
viewCanvas = document.getElementById('viewCanvas');//视图(可拖拽点击)canvas
//显示调色板选色器
generateColorSelectorHtml();
$('#brushToolBar').hide();
//事件绑定
{
var lastWindowWidth = window.innerWidth;
//窗口重绘后重设canvas尺寸
window.addEventListener('resize', function (e) {
//只有宽度真正改变时才继续,阻止移动设备上的拖拽误触发resize事件
if (lastWindowWidth == window.innerWidth) return;
lastWindowWidth = window.innerWidth;
if (!$('#mainContent').is(":hidden")) {
resizeViewCanvasFitWindow();
refreshImage();
}
}, false);
//图片加载事件
$('#imageChooser').change(function (e) {
$(this).next('.custom-file-label').html(e.target.files[0].name);//bootstrap的file控件不会自动赋值,需要手工显示
if (e.target.files.length <= 0) return;
let imageFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function (e) {
if (this.width > imageSizeLimit || this.height > imageSizeLimit) {
alert('图片分辨率' + this.width + 'x' + this.height + '过大,需小于' + imageSizeLimit + 'x' + imageSizeLimit);
return;
}
showLoadingMask(() => {
//重加载图片后的完整操作步骤:
//清空缓存和各种信息
similarColorCache = new Map();
paletteImageData = new Array();
sliceImages = new Array();
currentSliceImage = null;
largeCanvasOffsetX = 0;
largeCanvasOffsetY = 0;
colorReplaceList = new Map();
pixelColorReplaceList = new Map();
refreshColorReplaceList();
$('#mainContent').show();
let originalCtx = originalCanvas.getContext('2d');
originalCtx.clearRect(0, 0, originalCanvas.width, originalCanvas.height);
//绘制原图
originalCanvas.width = this.width;
originalCanvas.height = this.height;
originalCtx.drawImage(this, 0, 0);
//切掉原图白色和透明边
trimCanvas(originalCanvas);
//将原图颜色换成最相近的调色板颜色
toPaletteColor(originalCanvas, fullCanvas);
//将完整图片切成图块
sliceCanvasToImage(fullCanvas, 'sliceImageContainer');
//显示完整图片对应的马赛克大图
showFullImageView();
});
}
// 清空图片上传框的值
imageChooser.value = '';
};
reader.readAsDataURL(imageFile);
});
//拼豆品牌变化
$('#paletteSelect').change(function (e) {
if (this.value && allPalettes.has(this.value)) {
paletteMap = generatePaletteMap(allPalettes.get(this.value));//重新加载调色板
//刷新调色板选色器
generateColorSelectorHtml();
if (!$('#mainContent').is(':hidden')) {
showLoadingMask(() => {
//刷新调色板的完整操作步骤:
//清空缓存和各种信息
similarColorCache = new Map();
paletteImageData = new Array();
sliceImages = new Array();
currentSliceImage = null;
largeCanvasOffsetX = 0;
largeCanvasOffsetY = 0;
colorReplaceList = new Map();
pixelColorReplaceList = new Map();
refreshColorReplaceList();
//将原图颜色换成最相近的调色板颜色
toPaletteColor(originalCanvas, fullCanvas);
//将完整图片切成图块
sliceCanvasToImage(fullCanvas, 'sliceImageContainer');
//显示完整图片对应的马赛克大图
showFullImageView();
});
}
}
});
//拼板尺寸变化
$('#pieceSizeSelect').change(function (e) {
if (this.value && parseInt(this.value)) {
pieceSize = parseInt(this.value);
if (!$('#mainContent').is(':hidden')) {
resizeViewCanvasFitWindow();
refreshImage();
}
}
});
//点击显示全图
$(fullCanvas).on('click tap', function (e) {
showLoadingMask(() => {
showFullImageView();
});
});
//只显示某颜色按钮点击
$('#showSingleColor').on('click tap', function (e) {
$('#colorModal').modal('hide');
filterColor = selectedPixel.color;
refreshImage();
});
//替换单个像素按钮点击
$('#replacePixel').on('click tap', function (e) {
$('#colorModal').modal('hide');
if (!this.value) return;
//替换像素坐标使用的是全图真实坐标
let position = getRealPosition(selectedPixel.x, selectedPixel.y);
replacePixelColor(position.x, position.y, this.value);
refreshColorReplaceList();
refreshImage();
});
//替换相同颜色按钮点击
$('#replaceColor').on('click tap', function (e) {
$('#colorModal').modal('hide');
if (!this.value) return;
replaceColor(selectedPixel.color, this.value);
refreshColorReplaceList();
refreshImage();
});
//进入笔刷模式按钮点击
$('#replacePixelBrush').on('click tap', function (e) {
if (isBrushMode) return;
$('#colorModal').modal('hide');
isBrushMode = true;
brushColor = this.value;
$('#brushInfo').html("笔刷模式:<div class='colorBlock' style='color:" + getFontColor(brushColor) + "; background:#" + brushColor + ";'>" + paletteMap.get(brushColor).name + "</div>");
$('#brushToolBar').show();
});
//退出笔刷模式按钮点击
$('#disableBrushMode').on('click tap', function (e) {
isBrushMode = false;
brushColor = '';
$('#brushInfo').html('');
$('#brushToolBar').hide();
});
//关闭颜色对话框
$('#colorModal').on('hidden.bs.modal', function (e) {
//清除当前对话框中的所选值
selectedColor = null;
$("#colorSelector>div.selected").removeClass("selected");
$('#replacePixel').val('');
$('#replaceColor').val('');
});
//移除所有颜色替换选项
$('#removeAllColorReplace').on('click tap', function (e) {
colorReplaceList = new Map();
pixelColorReplaceList = new Map();
refreshColorReplaceList();
refreshImage();
});
//颜色替换选项导入/导出按钮
$('#showColorReplaceJsonModel').on('click tap', function (e) {
if (pixelColorReplaceList.size == 0 && colorReplaceList.size == 0) {
$('#colorReplaceJson').val('');
}
else {
//生成json
let jsonObj = {
pixelColorReplaceList: [...pixelColorReplaceList],
colorReplaceList: [...colorReplaceList]
};
$('#colorReplaceJson').val(JSON.stringify(jsonObj));
}
$("#copySuccessAlert").hide();
$("#importErrorAlert").hide();
$('#colorReplaceJsonModal').modal('show');
});
//复制颜色替换选项json到剪贴板
$('#copyColorReplaceJson').on('click tap', function (e) {
if ($('#colorReplaceJson').val().trim().length == 0) return;
$('#colorReplaceJson').select();
document.execCommand("Copy");//执行浏览器复制命令
$("#copySuccessAlert").show().delay(2000).slideUp(200, function () {
$(this).hide();
});
});
//导入颜色替换选项
$('#importColorReplaceJson').on('click tap', function (e) {
let json = $('#colorReplaceJson').val();
if (!json) return;
try {
let jsonObj = JSON.parse(json);
if (!jsonObj || !jsonObj.pixelColorReplaceList || !jsonObj.pixelColorReplaceList) {
console.log('json格式错误');
$("#importErrorAlert").show().delay(2000).slideUp(200, function () {
$(this).hide();
});
return;
}
pixelColorReplaceList = new Map(jsonObj.pixelColorReplaceList);
colorReplaceList = new Map(jsonObj.colorReplaceList);
refreshColorReplaceList();
refreshImage();
$('#colorReplaceJsonModal').modal('hide');
} catch (e) {
console.log(e);
$("#importErrorAlert").alert().delay(2000).slideUp(200, function () {
$(this).alert('close');
});
}
});
}
//视图互动事件
{
viewCanvas.onmousedown = function (e) {
if (e.buttons == 1 && largeCanvas) {//点击左键并且在大图已加载情况下开始拖拽
mousedownStartX = e.clientX;
mousedownStartY = e.clientY;
isMouseDown = true;
mousedownStartTime = new Date().getTime();
// isDragging = true;
}
};
viewCanvas.onmousemove = function (e) {
//鼠标按下且移动足够时间和距离后,判定为开始拖拽
if (isMouseDown & !isDragging) {
let mousedownTime = new Date().getTime() - mousedownStartTime;
if (mousedownTime > dragMinTimeSpan) {
let mousemoveDistance = Math.abs(mousedownStartX - e.clientX) + Math.abs(mousedownStartY - e.clientY);
if (mousemoveDistance > dragMinDistance) {
isDragging = true;
}
}
}
else if (isDragging && !isDrawingViewCanvas) {
//计算大图偏移值
largeCanvasOffsetX = largeCanvasStartOffsetX + mousedownStartX - e.clientX;
largeCanvasOffsetY = largeCanvasStartOffsetY + mousedownStartY - e.clientY;
if (largeCanvasOffsetX > largeCanvas.width - viewCanvas.width + 2 * (pixelSize + 1)) largeCanvasOffsetX = largeCanvas.width - viewCanvas.width + 2 * (pixelSize + 1);
if (largeCanvasOffsetX < 0) largeCanvasOffsetX = 0;
if (largeCanvasOffsetY > largeCanvas.height - viewCanvas.height + 2 * (pixelSize + 1)) largeCanvasOffsetY = largeCanvas.height - viewCanvas.height + 2 * (pixelSize + 1);
if (largeCanvasOffsetY < 0) largeCanvasOffsetY = 0;
requestAnimationFrame(function () {
showPartView();
});
}
};
viewCanvas.onmouseup = function (e) {
//鼠标按下但未拖拽时松开鼠标,触发点击
if (isMouseDown && !isDragging) {
viewCanvasClick(e);
}
isDragging = false;
isMouseDown = false;
largeCanvasStartOffsetX = largeCanvasOffsetX;
largeCanvasStartOffsetY = largeCanvasOffsetY;
};
viewCanvas.onmouseout = function (e) {
isDragging = false;
isMouseDown = false;
largeCanvasStartOffsetX = largeCanvasOffsetX;
largeCanvasStartOffsetY = largeCanvasOffsetY;
};
//触摸事件触发鼠标事件(移动端)
viewCanvas.ontouchstart = function (e) {
e.preventDefault();
let touch = e.touches[0];
viewCanvas.dispatchEvent(new MouseEvent("mousedown", {
buttons: 1,
clientX: touch.clientX,
clientY: touch.clientY
}));
};
viewCanvas.ontouchmove = function (e) {
e.preventDefault();
let touch = e.touches[0];
viewCanvas.dispatchEvent(new MouseEvent("mousemove", {
buttons: 1,
clientX: touch.clientX,
clientY: touch.clientY
}));
};
viewCanvas.ontouchend = function (e) {
e.preventDefault();
let touch = e.changedTouches[0];
viewCanvas.dispatchEvent(new MouseEvent("mouseup", {
buttons: 1,
clientX: touch.clientX,
clientY: touch.clientY
}));
};
viewCanvas.ontouchcancel = function (e) {
e.preventDefault();
viewCanvas.dispatchEvent(new MouseEvent("mouseout", {}));
};
}
});
//视图点击(触摸)操作
function viewCanvasClick(e) {
//实际在全图上的点击坐标
let rect = viewCanvas.getBoundingClientRect();
let realClickX = e.clientX - rect.left + largeCanvasOffsetX - (pixelSize + 1),
realClickY = e.clientY - rect.top + largeCanvasOffsetY - (pixelSize + 1);
//如果点在标尺上则不触发事件
if (realClickX < 0 || realClickX > viewCanvas.width + largeCanvasOffsetX - 2 * (pixelSize + 1)
|| realClickY < 0 || realClickY > viewCanvas.height + largeCanvasOffsetY - 2 * (pixelSize + 1)) return;
//如果当前正在过滤颜色,则恢复全部颜色
if (filterColor) {
filterColor = null;
refreshImage();
return;
}
//实际像素坐标
let pointX = ~~(realClickX / (pixelSize + 1)),
pointY = ~~(realClickY / (pixelSize + 1));
//全图真实坐标
let realPosition = getRealPosition(pointX, pointY);
let pointColorHex = getFullCanvasColor(realPosition.x, realPosition.y);//显示的颜色
if (!pointColorHex) return;//不操作透明像素和超出范围的像素
//如果处于笔刷模式则修改像素颜色
if (isBrushMode) {
replacePixelColor(realPosition.x, realPosition.y, brushColor);
refreshColorReplaceList();
refreshImage();
return;
}
let sourceColorHex = getFullImageColor(realPosition.x, realPosition.y);//原始颜色
let pointColor = paletteMap.get(pointColorHex);
if (sourceColorHex == pointColorHex) {
//未换色的情况
$('#colorInfo').html(" <strong>颜色</strong><div class='colorBlock' style='color:" + getFontColor(pointColorHex)
+ "; background:#" + pointColorHex + ";'>" + pointColor.name + "</div>#" + pointColorHex);
}
else {
//换色的情况
let sourceColor = paletteMap.get(sourceColorHex);
$('#colorInfo').html(" <strong>当前颜色</strong><div class='colorBlock' style='color:" + getFontColor(pointColorHex)
+ "; background:#" + pointColorHex + ";'>" + pointColor.name + "</div>#" + pointColorHex
+ " <strong>原始颜色</strong><div class='colorBlock' style='color:" + getFontColor(sourceColorHex)
+ "; background:#" + sourceColorHex + ";'>" + sourceColor.name + "</div>#" + sourceColorHex);
}
selectedPixel = { x: pointX, y: pointY, color: pointColorHex, name: pointColor.name };
$('#showSingleColor').html('只显示' + colorSum.get(pointColorHex) + '个' + pointColor.name);
$('#pointDialogTitle').html("<strong>大图坐标</strong>(" + (pointX + 1) + "," + (pointY + 1) + ")");
$('#colorToolBar').css('visibility', 'hidden');//占位隐藏工具栏
$('#colorModal').modal('show');
}
//获取全图指定坐标点对应的图片色值
function getFullCanvasColor(x, y) {
//根据当前显示的是全图还是切块,读取坐标所在rgb数据
let imageData, cursor;
let fullCtx = fullCanvas.getContext('2d');
imageData = fullCtx.getImageData(0, 0, fullCanvas.width, fullCanvas.height);
cursor = (y * fullCanvas.width + x) * 4;
if (cursor + 3 >= imageData.data.length) return null;//超出图像范围返回null
if (imageData.data[cursor + 3] == 0) return null;//透明色返回null
return rgbToHex(imageData.data[cursor], imageData.data[cursor + 1], imageData.data[cursor + 2]);
}
//获取换色原始图指定坐标点对应的图片色值
function getFullImageColor(x, y) {
let cursor = (y * paletteImageData.width + x) * 4;
if (paletteImageData.data[cursor + 3] == 0) return null;
return rgbToHex(paletteImageData.data[cursor], paletteImageData.data[cursor + 1], paletteImageData.data[cursor + 2]);
}
//去除canvas边缘的透明和白色像素
function trimCanvas(canvas) {
let ctx = canvas.getContext('2d'),
imageData = ctx.getImageData(0, 0, canvas.width, canvas.height),
bound = {
top: canvas.height,
left: canvas.width,
right: 0,
bottom: 0
};
for (let i = 0; i < imageData.data.length; i += 4) {
if (imageData.data[i + 3] !== 0
&& (imageData.data[i] < 250 || imageData.data[i + 1] < 250 || imageData.data[i + 2] < 250)) {//透明或者近似白色都作为白色去掉
let x = (i / 4) % canvas.width;
let y = ~~((i / 4) / canvas.width);
if (bound.top > y) bound.top = y;
if (bound.left > x) bound.left = x;
if (bound.right < x) bound.right = x;
if (bound.bottom < y) bound.bottom = y;
}
}
//取出裁剪图片的宽高
let trimHeight = bound.bottom - bound.top + 1,
trimWidth = bound.right - bound.left + 1,
trimmedImage = ctx.getImageData(bound.left, bound.top, trimWidth, trimHeight);
canvas.width = trimWidth;
canvas.height = trimHeight;
ctx.putImageData(trimmedImage, 0, 0);
}
//将canvas颜色输出为最相近的调色板颜色
function toPaletteColor(sourceCanvas, destCanvas) {
let sourceCtx = sourceCanvas.getContext('2d'),
destCtx = destCanvas.getContext('2d'),
imageData = sourceCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
//逐像素读取原图并寻找颜色值
for (let i = 0; i < imageData.data.length; i += 4) {
//读取颜色,如果透明则跳过
let a = imageData.data[i + 3];
if (a == 0) continue;
//加透明度选项
let r = ~~(imageData.data[i] * a / 255);
let g = ~~(imageData.data[i + 1] * a / 255);
let b = ~~(imageData.data[i + 2] * a / 255);
let x = (i / 4) % sourceCanvas.width;
let y = ~~((i / 4) / sourceCanvas.width);
//绘制调色板图
let similarColor = findSimilarColor(r, g, b);
imageData.data[i] = similarColor.r;
imageData.data[i + 1] = similarColor.g;
imageData.data[i + 2] = similarColor.b;
imageData.data[i + 3] = 255;//处理后一律变成不透明色
}
//保存换色后的原图
paletteImageData = imageData;
similarColorCache = null;
destCanvas.width = sourceCanvas.width;
destCanvas.height = sourceCanvas.height;
destCtx.putImageData(imageData, 0, 0);
}
//将canvas分割为小图并输出为可点击的image集合
function sliceCanvasToImage(canvas, sliceContainerName) {
let ctx = canvas.getContext('2d'),
rowCount = Math.ceil(canvas.height / pieceSize),//分割行数
colCount = Math.ceil(canvas.width / pieceSize);//分割列数
//生成table和image标签
let tableHtml = '';
for (let y = 0; y < rowCount; y++) {
tableHtml += "<tr>";
for (let x = 0; x < colCount; x++) {
tableHtml += "<td><img id='sliceImage-" + y + "_" + x + "' /></td>";
}
tableHtml += "</tr>";
}
$('#' + sliceContainerName).html(tableHtml);
//生成临时Canvas用于转换分割小图
let tempCanvas = document.createElement('canvas'),
tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = pieceSize;
tempCanvas.height = pieceSize;
tempCtx.font = ~~(pieceSize / 4) + 'px monospace';
tempCtx.strokeStyle = '#000';
tempCtx.textBaseline = 'bottom';
tempCtx.textAlign = 'right';
sliceImages = new Array(rowCount);
for (let y = 0; y < rowCount; y++) {
sliceImages[y] = new Array(colCount);
for (let x = 0; x < colCount; x++) {
tempCtx.clearRect(0, 0, pieceSize, pieceSize);
//如果宽高超出canvas则减小
let width = (x + 1 * pieceSize) > canvas.width ? canvas.width - x * pieceSize : pieceSize;
let height = (y + 1 * pieceSize) > canvas.height ? canvas.height - y * pieceSize : pieceSize;
let imageData = ctx.getImageData(x * pieceSize, y * pieceSize, width, height);
sliceImages[y][x] = imageData;
tempCtx.putImageData(imageData, 0, 0);
tempCtx.fillText((y + 1) + ',' + (x + 1), pieceSize, pieceSize);
let tempImageURL = tempCanvas.toDataURL("image/png");
let img = $('#sliceImage-' + y + '_' + x);
img.attr('src', tempImageURL);
img.click(function () {
showLoadingMask(() => {
currentSliceImage = { x: x, y: y };
showImageView(sliceImages[y][x]);
});
});
}
}
}
//生成全图的马赛克视图
function showFullImageView(keepOffset) {
currentSliceImage = null;
let imageData = fullCanvas.getContext('2d').getImageData(0, 0, fullCanvas.width, fullCanvas.height);
showImageView(imageData, fullCanvas.width, fullCanvas.height, keepOffset);
}
//生成指定图像数据马赛克视图
function showImageView(imageData, keepOffset) {
//首先绘制在largeCanvas上,再根据偏移坐标绘到viewCanvas
largeCanvas = document.createElement('canvas');
let largeCtx = largeCanvas.getContext('2d');
largeCanvas.width = imageData.width * (pixelSize + 1);
largeCanvas.height = imageData.height * (pixelSize + 1);
largeCtx.font = (~~(pixelSize / 2)) + 'px monospace';
largeCtx.strokeStyle = '#000';
largeCtx.textBaseline = 'middle';
largeCtx.textAlign = 'center';
//绘制标尺
drawRulers(imageData.width, imageData.height);
//绘制网格
largeCtx.beginPath();
for (let x = 1; x < imageData.width; x++) {
largeCtx.moveTo(x * (pixelSize + 1) - 0.5, 0);
largeCtx.lineTo(x * (pixelSize + 1) - 0.5, largeCanvas.height);
largeCtx.stroke();
}
for (let y = 1; y < imageData.height; y++) {
largeCtx.moveTo(0, y * (pixelSize + 1) - 0.5);
largeCtx.lineTo(largeCanvas.width, y * (pixelSize + 1) - 0.5);
largeCtx.stroke();
}
//逐像素读取原图并绘制大图
colorSum = new Map();//大图颜色统计
let totolBeadCount = 0;//总拼豆数
for (let i = 0; i < imageData.data.length; i += 4) {
//读取颜色,如果透明则跳过
let a = imageData.data[i + 3];
if (a == 0) continue;
let r = imageData.data[i];
let g = imageData.data[i + 1];
let b = imageData.data[i + 2];
let hex = rgbToHex(r, g, b);
//计算坐标
let x = (i / 4) % imageData.width;
let y = ~~((i / 4) / imageData.width);
// let realPosition = getRealPosition(x, y);
totolBeadCount++;
//绘制大像素块
largeCtx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
largeCtx.fillRect(x * (pixelSize + 1), y * (pixelSize + 1), pixelSize, pixelSize);
//写文字
largeCtx.fillStyle = getFontColor(r, g, b);//浅色黑字,深色白字
//统计颜色或出错信息
let color = paletteMap.get(hex);
if (color) {
if (colorSum.has(hex)) colorSum.set(hex, colorSum.get(hex) + 1);
else colorSum.set(hex, 1);
}
else {
console.log('Error color: ' + rgbToHex(r, g, b));
if (colorSum.has('Err')) colorSum.set('Err', colorSum.get('Err') + 1);
else colorSum.set('Err', 1);
}
largeCtx.fillText(color ? color.name : 'Err', x * (pixelSize + 1) + ~~(pixelSize * 0.5), y * (pixelSize + 1) + ~~(pixelSize * 0.5));
}
if (!keepOffset) {//保持拖拽偏移量不变(刷新时用)
largeCanvasStartOffsetX = 0, largeCanvasStartOffsetY = 0;
largeCanvasOffsetX = 0, largeCanvasOffsetY = 0;