Canvas取色法的实现

取色法是一种高效的图形拾取技术,其核心思想在于利用Canvas的像素操作API实现图形的快速识别与提取。在绘制图像的过程中,取色法会在另一个Canvas上同步生成一个具有相同坐标位置和大小的缓存图形,但每个图形对象都采用独特的颜色进行绘制,并且会保存一份图形颜色与图形对象的对照表。

在实际操作中,通过Canvas渲染上下文对象提供的ctx.getImageData(x, y, 1, 1)方法,可以精确地获取指定位置像素的颜色信息。由于缓存图形中的颜色都是唯一的,因此可以迅速从颜色对照表中找到对应的图形对象,实现精准拾取。需要注意的是,ctx.getImageData()方法返回的数据中包含了data属性,该属性为Uint8ClampedArray类型,存储了像素数据。每个像素由四个字节的值构成,分别代表红、绿、蓝和透明度(r,g,b,a)。

对于常见的几何图形,取色法可以直接在缓存图形上进行绘制。然而,对于文本和图像这类较为复杂的图形对象,则需要将其转换为矩形,并以矩形的方式绘制在缓存图形中。这样做可以确保取色法的有效性和准确性,使其能够广泛应用于各种场景。

通过取色法,我们可以从一张包含多种图形对象的图像中快速、准确地拾取目标对象。这种方法不仅提高了图形拾取的效率,还增强了图形处理的灵活性和可扩展性。因此,取色法在图形处理领域具有广泛的应用前景。

示例效果与源代码:

运行效果

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
<!DOCTYPE html>
<html>

<head>
<title>点图查询-取色法</title>
<meta charset="UTF-8">
<!-- frame所需脚本和样式 -->
<script type="text/javascript" src="/examples/script/lib/jquery-1.11.2.min.js"></script>
<link type="text/css" rel="stylesheet" href="/examples/script/bootstrap-3.3.5/css/bootstrap.min.css">
<script src="/examples/graph/js/helper.js"></script>
</head>

<body style="overflow: hidden; margin:10px;">
<div id="graphWrapper" style="width:500px; height:500px; border:solid 1px #CCC;"></div>
<div id="graphColor" style="position:absolute; left:520px; top:10px; width:500px; height:500px; border:solid 1px #CCC; background-image: url('/examples/graph/images/transparent.png');">
</div>
<div style="margin:10px; text-align: left;">
<div class="checkbox" style="font-size: 16px;">
<label style="margin-right:20px"><input id="chkPoint" type="checkbox"></label>
<label style="margin-right:20px"><input id="chkRect" type="checkbox">矩形</label>
<label style="margin-right:20px"><input id="chkPolyline" type="checkbox">线</label>
<label style="margin-right:20px"><input id="chkPolygon" type="checkbox">多边形</label>
<label style="margin-right:20px"><input id="chkCircle" type="checkbox">圆形</label>
<label style="margin-right:20px"><input id="chkEllipse" type="checkbox">椭圆</label>
<label style="margin-right:20px"><input id="chkText" type="checkbox">文字</label>
</div>
</div>
</body>
<script type="module">
import {
Graph, Layer, VectorSource, debug, Color, MathUtil, Collide, circle2LineRing, getStarLineRing,
GGeometryType, Rect, Point, Circle, Ellipse, Text, Polyline, Polygon, EventType
} from "/examples/src/index.js";

// graph对象
let graph = new Graph({
"target": "graphWrapper",
"hitGetColor": true
});

// 网格水印层
let debugLayer = debug.generateGrid(Object.assign({ "interval": 10, "graph": graph }, graph.getSize()));
debugLayer.getSource().add(new Text({
"text": "按点拾取(取色法)Demo",
"x": graph.getSize().width / 2,
"y": graph.getSize().height / 2,
"vectorSize": false,
"style": { "fillColor": "#D0D0D0", "fontSize": 30, "fontName": "黑体", "textAlign": "center", "textBaseline": "middle" }
}));

// 新建绘图图层
let layer = graph.addLayer();
// 浮动层
let overLayer = graph.addOverLayer();

let lastPosition = [0, 0];

// pageload
$(document).ready(function () {

let colorCanvas = graph.getRenderer().getHitImage();
$("#graphColor").append(colorCanvas);

let tmpCanvas = document.createElement("canvas");
$("#graphColor").append(tmpCanvas)
tmpCanvas.width = colorCanvas.width;
tmpCanvas.height = colorCanvas.height;
tmpCanvas.style.position = "absolute";
tmpCanvas.style.top = 0;
tmpCanvas.style.left = 0;
let ctxColor = tmpCanvas.getContext('2d');

// 鼠标移动事件
graph.getRenderObject().on('mousemove', function (e) {
let point = [e.offsetX, e.offsetY];
let coord = graph.getCoordinateFromPixel(point, true);

// 清空浮动层数据
overLayer.getSource().clearData();

// 碰撞检测
_collideCheck(point);

// 鼠标位置点
overLayer.getSource().add(new Point({
"x": coord[0],
"y": coord[1],
"size": -5,
"style": { "fillColor": "blue", "fillStyle": 1, "color": "none" }
}));

lastPosition = [point[0], point[1]];
});

// 在颜色Canvas上绘制圆点
graph.on(EventType.RenderAfter, function (args) {
ctxColor.clearRect(0, 0, ctxColor.canvas.width, ctxColor.canvas.height);
// 绘制圆点
ctxColor.beginPath();
ctxColor.arc(lastPosition[0], lastPosition[1], 3, 0, 2*Math.PI);
ctxColor.fillStyle = "blue";
ctxColor.fill();
});

// 取色法进行碰撞检测
function _collideCheck(coord) {
// 显示颜色值
let hitColor = graph.getRenderer().getColor(coord);
if (hitColor) {
if (graph.viewGeomList.has(hitColor)) {
let geom = graph.viewGeomList.get(hitColor).clone();
geom.setStyle({ "fillColor": "#FF2020", "color": "#FF2020", "lineWidth":4 });
overLayer.getSource().add(geom);
return true;
}
}
return false;
}

// 复选框状态事件:清空或随机生成对象
$("#chkPoint").on("change", function () {
if ($(this).prop("checked")) {
for (let i = 0; i < MathUtil.getRandomNum(6, 10); i++) {
layer.getSource().add(new Point({
"x": MathUtil.getRandomNum(50, 450),
"y": MathUtil.getRandomNum(50, 450),
"size": MathUtil.getRandomNum(10, 20),
"style": { "fillColor": "#FFDFDF", "fillStyle": 1, "lineWidth": 1, "color": "#FFA5E8" }
}));
}
} else {
layer.getSource().clearTypeData(GGeometryType.POINT);
}
graph.render();
});

// 复选框状态事件:清空或随机生成对象
$("#chkRect").on("change", function () {
if ($(this).prop("checked")) {
for (let i = 0; i < MathUtil.getRandomNum(3, 5); i++) {
layer.getSource().add(new Rect({
"x": MathUtil.getRandomNum(50, 450),
"y": MathUtil.getRandomNum(50, 450),
"width": MathUtil.getRandomNum(40, 70),
"height": MathUtil.getRandomNum(20, 40),
"style": { "fillColor": "#FFDFDF", "fillStyle": 1, "lineWidth": 1, "color": "#FFA5E8" }
}));
}
} else {
layer.getSource().clearTypeData(GGeometryType.RECT);
}
graph.render();
});

$("#chkCircle").on("change", function () {
if ($(this).prop("checked")) {
for (let i = 0; i < MathUtil.getRandomNum(3, 5); i++) {
layer.getSource().add(new Circle({
"x": MathUtil.getRandomNum(50, 450),
"y": MathUtil.getRandomNum(50, 450),
"radius": MathUtil.getRandomNum(20, 40),
"style": { "fillColor": "#DFFFBF", "fillStyle": 1, "lineWidth": 1, "color": "#FFA5E8" }
}));
}
} else {
layer.getSource().clearTypeData(GGeometryType.CIRCLE);
}
graph.render();
});

$("#chkText").on("change", function () {
if ($(this).prop("checked")) {
for (let i = 0; i < MathUtil.getRandomNum(3, 5); i++) {
layer.getSource().add(new Text({
"x": MathUtil.getRandomNum(50, 450),
"y": MathUtil.getRandomNum(50, 450),
"rotation": MathUtil.getRandomNum(0, 90),
"text": "碰撞检测文本",
"style": { "fontSize": 24, "fontName": "黑体", "fillColor": "#0000FF", }
}));
}
} else {
layer.getSource().clearTypeData(GGeometryType.TEXT);
}
graph.render();
});

$("#chkEllipse").on("change", function () {
if ($(this).prop("checked")) {
for (let i = 0; i < MathUtil.getRandomNum(2, 4); i++) {
layer.getSource().add(new Ellipse({
"x": MathUtil.getRandomNum(50, 450),
"y": MathUtil.getRandomNum(50, 450),
"radiusX": MathUtil.getRandomNum(20, 40),
"radiusY": MathUtil.getRandomNum(20, 20),
"style": { "fillColor": "#9FFFFF", "fillStyle": 1, "lineWidth": 1, "color": "#FFA5E8" }
}));
}
} else {
layer.getSource().clearTypeData(GGeometryType.ELLIPSE);
}
graph.render();
});

$("#chkPolyline").on("change", function () {
if ($(this).prop("checked")) {
for (let i = 0; i < MathUtil.getRandomNum(3, 5); i++) {
let [x, y] = [MathUtil.getRandomNum(50, 400), MathUtil.getRandomNum(50, 400)];
layer.getSource().add(new Polyline({
"coords": [[x, y], [x + MathUtil.getRandomNum(10, 300), y + MathUtil.getRandomNum(-100, 100)]],
"style": { "lineWidth": 4, "color": "#00957D" }
}));
}
} else {
layer.getSource().clearTypeData(GGeometryType.POLYLINE);
}
graph.render();
});

$("#chkPolygon").on("change", function () {
if ($(this).prop("checked")) {
for (let i = 0; i < MathUtil.getRandomNum(3, 5); i++) {
let center = [MathUtil.getRandomNum(150, 400), MathUtil.getRandomNum(50, 400)];
let sideNum = MathUtil.getRandomNum(3, 8);
let radius = MathUtil.getRandomNum(20, 40);
layer.getSource().add(new Polygon({
"coords": circle2LineRing(center, radius, sideNum),
"style": { "fillColor": "#E5FFF5", "fillStyle": 1, "lineWidth": 1, "color": "#FF9F9F" }
}));

center = [MathUtil.getRandomNum(150, 620), MathUtil.getRandomNum(50, 400)];
layer.getSource().add(new Polygon({
"coords": getStarLineRing(center, radius, null, sideNum >= 6 ? sideNum - 3 : sideNum),
"style": { "fillColor": "#E5FFF5", "fillStyle": 1, "lineWidth": 1, "color": "#FF9F9F" }
}));
}
} else {
layer.getSource().clearTypeData(GGeometryType.POLYGON);
}
graph.render();
});
})

</script>

</html>

尝试一下 »