• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

antvis / G2Plot / 17846812917

19 Sep 2025 02:35AM UTC coverage: 94.901% (-0.2%) from 95.064%
17846812917

push

github

web-flow
fix: 更新G2依赖 (#3868)

Co-authored-by: 荊芥 <shensiqi.ssq@alibaba-inc.com>

2381 of 2721 branches covered (87.5%)

Branch coverage included in aggregate %.

6944 of 7105 relevant lines covered (97.73%)

421675.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.93
/src/utils/transform/word-cloud.ts
1
import { assign, isFunction, isNil } from '@antv/util';
2
import { Tag, Word } from '../../plots/word-cloud/types';
5,915✔
3

5,915✔
4
type FontWeight = number | 'normal' | 'bold' | 'bolder' | 'lighter';
5,915✔
5

5,915✔
6
export interface Options {
1,350✔
7
  size: [number, number];
8
  font?: string | ((row: Word, index?: number, words?: Word[]) => string);
9
  fontSize?: number | ((row: Word, index?: number, words?: Word[]) => number);
10
  fontWeight?: FontWeight | ((row: Word, index?: number, words?: Word[]) => FontWeight);
11
  rotate?: number | ((row: Word, index?: number, words?: Word[]) => number);
12
  padding?: number | ((row: Word, index?: number, words?: Word[]) => number);
13
  spiral?: 'archimedean' | 'rectangular' | ((size: [number, number]) => (t: number) => number[]);
14
  random?: number | (() => number);
15
  timeInterval?: number;
16
  imageMask?: HTMLImageElement;
17
}
18

19
const DEFAULT_OPTIONS: Options = {
20
  font: () => 'serif',
21
  padding: 1,
22
  size: [500, 500],
23
  spiral: 'archimedean', // 'archimedean' || 'rectangular' || {function}
860✔
24
  // timeInterval: Infinity // max execute time
860✔
25
  timeInterval: 3000, // max execute time
26
  // imageMask: '', // instance of Image, must be loaded
5,915✔
27
};
28

29
/**
30
 * 根据对应的数据对象,计算每个
31
 * 词语在画布中的渲染位置,并返回
32
 * 计算后的数据对象
33
 * @param words
34
 * @param options
1,010✔
35
 */
1,010✔
36
export function wordCloud(words: Word[], options?: Partial<Options>): Tag[] {
9,090✔
37
  // 混入默认配置
6,640✔
38
  options = assign({} as Options, DEFAULT_OPTIONS, options);
39
  return transform(words, options as Options);
40
}
1,010✔
41

1,010✔
42
/**
60✔
43
 * 抛出没有混入默认配置的方法,用于测试。
44
 * @param words
1,010✔
45
 * @param options
1,010✔
46
 */
1,010✔
47
export function transform(words: Word[], options: Options) {
7,559✔
48
  // 布局对象
7,559✔
49
  const layout = tagCloud();
50
  ['font', 'fontSize', 'fontWeight', 'padding', 'rotate', 'size', 'spiral', 'timeInterval', 'random'].forEach(
1,010✔
51
    (key: string) => {
52
      if (!isNil(options[key])) {
53
        layout[key](options[key]);
54
      }
55
    }
1,010✔
56
  );
57

58
  layout.words(words);
59
  if (options.imageMask) {
60
    layout.createMask(options.imageMask);
61
  }
62

1,010✔
63
  const result = layout.start();
64
  const tags: any[] = result._tags;
65

66
  tags.forEach((tag) => {
67
    tag.x += options.size[0] / 2;
68
    tag.y += options.size[1] / 2;
69
  });
1,010✔
70

71
  const [w, h] = options.size;
5,915✔
72
  // 添加两个参照数据,分别表示左上角和右下角。
5,915✔
73
  // 不添加的话不会按照真实的坐标渲染,而是以
74
  // 数据中的边界坐标为边界进行拉伸,以铺满画布。
41,970✔
75
  // 这样的后果会导致词语之间的重叠。
76
  tags.push({
77
    text: '',
1,350✔
78
    value: 0,
79
    x: 0,
80
    y: 0,
44,670✔
81
    opacity: 0,
82
  });
83
  tags.push({
2,700✔
84
    text: '',
85
    value: 0,
86
    x: w,
2,430✔
87
    y: h,
88
    opacity: 0,
89
  });
1,080✔
90

91
  return tags;
92
}
93

94
/*
9,727✔
95
 * Synchronous version of d3-cloud
8,807✔
96
 */
920✔
97
// Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/
920✔
98
// Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf
920✔
99
/* eslint-disable no-return-assign, no-cond-assign */
920✔
100

920✔
101
interface Item {
920✔
102
  value: number;
41,370✔
103
  text: string;
41,370✔
104
  sprite: boolean;
41,370✔
105
}
41,370✔
106

41,370✔
107
const cloudRadians = Math.PI / 180,
22,074✔
108
  cw = (1 << 11) >> 5,
22,074✔
109
  ch = 1 << 11;
22,074✔
110

111
function cloudText(d: Item) {
112
  return d.text;
19,296✔
113
}
114

41,370✔
115
function cloudFont() {
8,327✔
116
  return 'serif';
41,370✔
117
}
2,730✔
118

2,730✔
119
function cloudFontNormal() {
2,730✔
120
  return 'normal';
121
}
41,370!
122

×
123
function cloudFontSize(d: Item) {
41,370✔
124
  return d.value;
41,370✔
125
}
22,074✔
126

41,370✔
127
function cloudRotate() {
41,370!
128
  return ~~(Math.random() * 2) * 90;
41,370✔
129
}
41,370✔
130

131
function cloudPadding() {
41,370✔
132
  return 1;
41,370✔
133
}
41,370✔
134

41,370✔
135
// Fetches a monochrome sprite bitmap for the specified text.
41,370✔
136
// Load in batches for speed.
41,370✔
137
function cloudSprite(contextAndRatio, d, data, di) {
41,370✔
138
  if (d.sprite) return;
41,370✔
139
  const c = contextAndRatio.context,
41,370✔
140
    ratio = contextAndRatio.ratio;
41,370✔
141

41,370✔
142
  c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
143
  let x = 0,
920✔
144
    y = 0,
920✔
145
    maxh = 0;
41,430✔
146
  const n = data.length;
41,430!
147
  --di;
×
148
  while (++di < n) {
41,430✔
149
    d = data[di];
41,430✔
150
    c.save();
151
    c.font = d.style + ' ' + d.weight + ' ' + ~~((d.size + 1) / ratio) + 'px ' + d.font;
41,430✔
152
    let w = c.measureText(d.text + 'm').width * ratio,
19,304,062✔
153
      h = d.size << 1;
41,430✔
154
    if (d.rotate) {
41,430!
155
      const sr = Math.sin(d.rotate * cloudRadians),
×
156
        cr = Math.cos(d.rotate * cloudRadians),
41,430✔
157
        wcr = w * cr,
41,430✔
158
        wsr = w * sr,
41,430✔
159
        hcr = h * cr,
4,427,848✔
160
        hsr = h * sr;
617,729,984✔
161
      w = ((Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5) << 5;
617,729,984✔
162
      h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
617,729,984✔
163
    } else {
164
      w = ((w + 0x1f) >> 5) << 5;
4,427,848✔
165
    }
4,040,767✔
166
    if (h > maxh) maxh = h;
167
    if (x + w >= cw << 5) {
387,081✔
168
      x = 0;
387,081✔
169
      y += maxh;
387,081✔
170
      maxh = 0;
387,081✔
171
    }
172
    if (y + h >= ch) break;
173
    c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
41,430✔
174
    if (d.rotate) c.rotate(d.rotate * cloudRadians);
41,430✔
175
    c.fillText(d.text, 0, 0);
176
    if (d.padding) {
177
      c.lineWidth = 2 * d.padding;
178
      c.strokeText(d.text, 0, 0);
179
    }
7,891,958✔
180
    c.restore();
7,891,958✔
181
    d.width = w;
7,891,958✔
182
    d.height = h;
7,891,958✔
183
    d.xoff = x;
60,344,005✔
184
    d.yoff = y;
60,344,005✔
185
    d.x1 = w >> 1;
215,661,240✔
186
    d.y1 = h >> 1;
7,082,318✔
187
    d.x0 = -d.x1;
188
    d.y0 = -d.y1;
53,261,687✔
189
    d.hasText = true;
190
    x += w;
809,640✔
191
  }
192
  const pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
193
    sprite = [];
6,406✔
194
  while (--di >= 0) {
6,406✔
195
    d = data[di];
1,069✔
196
    if (!d.hasText) continue;
6,406✔
197
    const w = d.width,
1,165✔
198
      w32 = w >> 5;
6,406✔
199
    let h = d.y1 - d.y0;
860✔
200
    // Zero the buffer
6,406✔
201
    for (let i = 0; i < h * w32; i++) sprite[i] = 0;
1,229✔
202
    x = d.xoff;
203
    if (x == null) return;
204
    y = d.yoff;
809,640✔
205
    let seen = 0,
206
      seenRow = -1;
207
    for (let j = 0; j < h; j++) {
9,607✔
208
      for (let i = 0; i < w; i++) {
9,607✔
209
        const k = w32 * j + (i >> 5),
24,361,680✔
210
          m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
211
        sprite[k] |= m;
212
        seen |= m;
213
      }
30✔
214
      if (seen) seenRow = j;
30✔
215
      else {
30✔
216
        d.y0++;
30!
217
        h--;
218
        j--;
30!
219
        y++;
220
      }
30✔
221
    }
30✔
222
    d.y1 = d.y0 + seenRow;
223
    d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
×
224
  }
×
225
}
226

×
227
// Use mask-based collision detection.
×
228
function cloudCollide(tag, board, sw) {
229
  sw >>= 5;
×
230
  const sprite = tag.sprite,
×
231
    w = tag.width >> 5,
232
    lx = tag.x - (w << 4),
30✔
233
    sx = lx & 0x7f,
234
    msx = 32 - sx,
235
    h = tag.y1 - tag.y0;
236
  let x = (tag.y + tag.y0) * sw + (lx >> 5),
237
    last;
1,010✔
238
  for (let j = 0; j < h; j++) {
1,010✔
239
    last = 0;
1,010✔
240
    for (let i = 0; i <= w; i++) {
8,814,640✔
241
      if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true;
1,010✔
242
    }
243
    x += sw;
244
  }
1,010✔
245
  return false;
246
}
247

11,320✔
248
function cloudBounds(bounds, d) {
249
  const b0 = bounds[0],
250
    b1 = bounds[1];
127,140✔
251
  if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
252
  if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
253
  if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
5,915✔
254
  if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
5,915✔
255
}
256

257
function collideRects(a, b) {
258
  return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y;
259
}
1,010✔
260

1,010✔
261
function archimedeanSpiral(size) {
1,010✔
262
  const e = size[0] / size[1];
1,010✔
263
  return function (t) {
1,010✔
264
    return [e * (t *= 0.1) * Math.cos(t), t * Math.sin(t)];
1,010✔
265
  };
1,010✔
266
}
1,010✔
267

268
function rectangularSpiral(size) {
41,970✔
269
  const dy = 4,
41,970✔
270
    dx = (dy * size[0]) / size[1];
41,970✔
271
  let x = 0,
41,970✔
272
    y = 0;
41,970✔
273
  return function (t) {
41,970✔
274
    const sign = t < 0 ? -1 : 1;
41,970✔
275
    // See triangular numbers: T_n = n * (n + 1) / 2.
41,970✔
276
    switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
277
      case 0:
278
        x += dx;
172,144✔
279
        break;
280
      case 1:
1,010✔
281
        y += dy;
282
        break;
283
      case 2:
284
        x -= dx;
285
        break;
286
      default:
287
        y -= dy;
288
        break;
289
    }
290
    return [x, y];
291
  };
292
}
1,010✔
293

294
// TODO reuse arrays?
1,010✔
295
function zeroArray(n) {
1,010✔
296
  const a = [];
9,727✔
297
  let i = -1;
9,727✔
298
  while (++i < n) a[i] = 0;
9,727✔
299
  return a;
9,727✔
300
}
9,727✔
301

7,559✔
302
function cloudCanvas() {
7,559✔
303
  return document.createElement('canvas');
6,676✔
304
}
305

6,406✔
306
export function functor(d) {
307
  return isFunction(d)
308
    ? d
309
    : function () {
883✔
310
        return d;
311
      };
312
}
313

314
const spirals = {
315
  archimedean: archimedeanSpiral,
7,559✔
316
  rectangular: rectangularSpiral,
7,559✔
317
};
318

319
function tagCloud() {
1,010✔
320
  let size = [256, 256],
1,010✔
321
    font = cloudFont,
322
    fontSize = cloudFontSize,
1,010✔
323
    fontWeight = cloudFontNormal,
324
    rotate = cloudRotate,
325
    padding = cloudPadding,
1,010✔
326
    spiral = archimedeanSpiral,
1,010✔
327
    random = Math.random,
328
    words = [],
1,010✔
329
    timeInterval = Infinity;
1,010✔
330

1,010✔
331
  const text = cloudText;
1,010✔
332
  const fontStyle = cloudFontNormal;
1,010✔
333
  const canvas = cloudCanvas;
1,010✔
334
  const cloud: any = {};
335

336
  cloud.start = function () {
337
    const [width, height] = size;
9,727✔
338
    const contextAndRatio = getContext(canvas()),
9,727✔
339
      board = cloud.board ? cloud.board : zeroArray((size[0] >> 5) * size[1]),
9,727✔
340
      n = words.length,
24,384,330✔
341
      tags = [],
24,384,330✔
342
      data = words
24,384,330✔
343
        .map(function (d, i, data) {
2,168✔
344
          d.text = text.call(this, d, i, data);
24,382,162✔
345
          d.font = font.call(this, d, i, data);
24,382,162✔
346
          d.style = fontStyle.call(this, d, i, data);
24,382,162✔
347
          d.weight = fontWeight.call(this, d, i, data);
16,489,321✔
348
          d.rotate = rotate.call(this, d, i, data);
349
          d.size = ~~fontSize.call(this, d, i, data);
7,892,841✔
350
          d.padding = padding.call(this, d, i, data);
810,523✔
351
          return d;
7,559✔
352
        })
7,559✔
353
        .sort(function (a, b) {
7,559✔
354
          return b.size - a.size;
612,124✔
355
        });
612,124✔
356
    let i = -1,
3,179,906✔
357
      bounds = !cloud.board
358
        ? null
612,124✔
359
        : [
360
            {
7,559✔
361
              x: 0,
7,559✔
362
              y: 0,
363
            },
364
            {
365
              x: width,
2,168✔
366
              y: height,
367
            },
1,010✔
368
          ];
60✔
369

60✔
370
    step();
371

60✔
372
    function step() {
30✔
373
      const start = Date.now();
374
      while (Date.now() - start < timeInterval && ++i < n) {
30✔
375
        const d = data[i];
30✔
376
        d.x = (width * (random() + 0.5)) >> 1;
30✔
377
        d.y = (height * (random() + 0.5)) >> 1;
30✔
378
        cloudSprite(contextAndRatio, d, data, i);
30✔
379
        if (d.hasText && place(board, d, bounds)) {
30✔
380
          tags.push(d);
30✔
381
          if (bounds) {
30✔
382
            if (!cloud.hasImage) {
15,000✔
383
              // update bounds if image mask not set
7,500,000✔
384
              cloudBounds(bounds, d);
7,500,000✔
385
            }
7,500,000✔
386
          } else {
7,500,000✔
387
            bounds = [
7,500,000✔
388
              { x: d.x + d.x0, y: d.y + d.y0 },
389
              { x: d.x + d.x1, y: d.y + d.y1 },
390
            ];
30✔
391
          }
30✔
392
          // Temporary hack
393
          d.x -= size[0] >> 1;
1,010✔
394
          d.y -= size[1] >> 1;
890!
395
        }
396
      }
1,010✔
397
      cloud._tags = tags;
1,010✔
398
      cloud._bounds = bounds;
399
    }
1,010✔
400

1,010✔
401
    return cloud;
402
  };
1,010✔
403

860✔
404
  function getContext(canvas: HTMLCanvasElement) {
405
    canvas.width = canvas.height = 1;
1,010✔
406
    const ratio = Math.sqrt(
680✔
407
      (canvas.getContext('2d', { willReadFrequently: true }) as CanvasRenderingContext2D)!.getImageData(0, 0, 1, 1).data
408
        .length >> 2
1,010✔
409
    );
710✔
410
    canvas.width = (cw << 5) / ratio;
411
    canvas.height = ch / ratio;
1,010✔
412

860✔
413
    const context = canvas.getContext('2d', { willReadFrequently: true }) as CanvasRenderingContext2D;
414
    context.fillStyle = context.strokeStyle = 'red';
1,010✔
415
    context.textAlign = 'center';
680✔
416
    return { context, ratio };
417
  }
1,010✔
418

890✔
419
  function place(board, tag, bounds) {
420
    // const perimeter = [{ x: 0, y: 0 }, { x: size[0], y: size[1] }],
1,010✔
421
    const startX = tag.x,
60✔
422
      startY = tag.y,
423
      maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),
1,010✔
424
      s = spiral(size),
425
      dt = random() < 0.5 ? 1 : -1;
426
    let dxdy,
427
      t = -dt,
428
      dx,
429
      dy;
430

431
    while ((dxdy = s((t += dt)))) {
432
      dx = ~~dxdy[0];
433
      dy = ~~dxdy[1];
434

435
      if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;
436

437
      tag.x = startX + dx;
438
      tag.y = startY + dy;
439

440
      if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
441
      // TODO only check for collisions within current bounds.
442
      if (!bounds || !cloudCollide(tag, board, size[0])) {
443
        if (!bounds || collideRects(tag, bounds)) {
444
          const sprite = tag.sprite,
445
            w = tag.width >> 5,
446
            sw = size[0] >> 5,
447
            lx = tag.x - (w << 4),
448
            sx = lx & 0x7f,
449
            msx = 32 - sx,
450
            h = tag.y1 - tag.y0;
451
          let last,
452
            x = (tag.y + tag.y0) * sw + (lx >> 5);
453
          for (let j = 0; j < h; j++) {
454
            last = 0;
455
            for (let i = 0; i <= w; i++) {
456
              board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
457
            }
458
            x += sw;
459
          }
460
          delete tag.sprite;
461
          return true;
462
        }
463
      }
464
    }
465
    return false;
466
  }
467

468
  cloud.createMask = (img: HTMLImageElement) => {
469
    const can: HTMLCanvasElement = document.createElement('canvas');
470
    const [width, height] = size;
471

472
    // 当 width 或 height 为 0 时,调用 cxt.getImageData 会报错
473
    if (!width || !height) {
474
      return;
475
    }
476
    const w32 = width >> 5;
477
    const board = zeroArray((width >> 5) * height);
478
    can.width = width;
479
    can.height = height;
480
    const cxt = can.getContext('2d') as CanvasRenderingContext2D;
481
    cxt.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
482
    const imageData = cxt.getImageData(0, 0, width, height).data;
483
    for (let j = 0; j < height; j++) {
484
      for (let i = 0; i < width; i++) {
485
        const k = w32 * j + (i >> 5);
486
        const tmp = (j * width + i) << 2;
487
        const flag = imageData[tmp] >= 250 && imageData[tmp + 1] >= 250 && imageData[tmp + 2] >= 250;
488
        const m = flag ? 1 << (31 - (i % 32)) : 0;
489
        board[k] |= m;
490
      }
491
    }
492
    cloud.board = board;
493
    cloud.hasImage = true;
494
  };
495

496
  cloud.timeInterval = function (_) {
497
    timeInterval = _ == null ? Infinity : _;
498
  };
499

500
  cloud.words = function (_) {
501
    words = _;
502
  };
503

504
  cloud.size = function (_) {
505
    size = [+_[0], +_[1]];
506
  };
507

508
  cloud.font = function (_) {
509
    font = functor(_);
510
  };
511

512
  cloud.fontWeight = function (_) {
513
    fontWeight = functor(_);
514
  };
515

516
  cloud.rotate = function (_) {
517
    rotate = functor(_);
518
  };
519

520
  cloud.spiral = function (_) {
521
    spiral = spirals[_] || _;
522
  };
523

524
  cloud.fontSize = function (_) {
525
    fontSize = functor(_);
526
  };
527

528
  cloud.padding = function (_) {
529
    padding = functor(_);
530
  };
531

532
  cloud.random = function (_) {
533
    random = functor(_);
534
  };
535

536
  return cloud;
537
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc