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

antvis / G2Plot / 3664751189

pending completion
3664751189

push

github

GitHub
fix: close issues (#3419)

2325 of 2656 branches covered (87.54%)

Branch coverage included in aggregate %.

6896 of 7054 relevant lines covered (97.76%)

412587.74 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,818✔
3

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

5,818✔
6
export interface Options {
1,260✔
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],
789✔
23
  spiral: 'archimedean', // 'archimedean' || 'rectangular' || {function}
789✔
24
  // timeInterval: Infinity // max execute time
25
  timeInterval: 3000, // max execute time
5,818✔
26
  // imageMask: '', // instance of Image, must be loaded
27
};
28

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

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

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

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;
929✔
69
  });
70

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

91
  return tags;
92
}
93

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

845✔
101
interface Item {
37,848✔
102
  value: number;
37,848✔
103
  text: string;
37,848✔
104
  sprite: boolean;
37,848✔
105
}
37,848✔
106

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

111
function cloudText(d: Item) {
17,545✔
112
  return d.text;
113
}
37,848✔
114

8,351✔
115
function cloudFont() {
37,848✔
116
  return 'serif';
2,527✔
117
}
2,527✔
118

2,527✔
119
function cloudFontNormal() {
120
  return 'normal';
37,848!
121
}
×
122

37,848✔
123
function cloudFontSize(d: Item) {
37,848✔
124
  return d.value;
20,303✔
125
}
37,848✔
126

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

37,848✔
131
function cloudPadding() {
37,848✔
132
  return 1;
37,848✔
133
}
37,848✔
134

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

142
  c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
845✔
143
  let x = 0,
845✔
144
    y = 0,
37,848✔
145
    maxh = 0;
37,848!
146
  const n = data.length;
×
147
  --di;
37,848✔
148
  while (++di < n) {
37,848✔
149
    d = data[di];
150
    c.save();
37,848✔
151
    c.font = d.style + ' ' + d.weight + ' ' + ~~((d.size + 1) / ratio) + 'px ' + d.font;
17,367,324✔
152
    let w = c.measureText(d.text + 'm').width * ratio,
37,848✔
153
      h = d.size << 1;
37,848!
154
    if (d.rotate) {
×
155
      const sr = Math.sin(d.rotate * cloudRadians),
37,848✔
156
        cr = Math.cos(d.rotate * cloudRadians),
37,848✔
157
        wcr = w * cr,
37,848✔
158
        wsr = w * sr,
3,960,008✔
159
        hcr = h * cr,
555,754,368✔
160
        hsr = h * sr;
555,754,368✔
161
      w = ((Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5) << 5;
555,754,368✔
162
      h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
163
    } else {
3,960,008✔
164
      w = ((w + 0x1f) >> 5) << 5;
3,611,811✔
165
    }
166
    if (h > maxh) maxh = h;
348,197✔
167
    if (x + w >= cw << 5) {
348,197✔
168
      x = 0;
348,197✔
169
      y += maxh;
348,197✔
170
      maxh = 0;
171
    }
172
    if (y + h >= ch) break;
37,848✔
173
    c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
37,848✔
174
    if (d.rotate) c.rotate(d.rotate * cloudRadians);
175
    c.fillText(d.text, 0, 0);
176
    if (d.padding) {
177
      c.lineWidth = 2 * d.padding;
178
      c.strokeText(d.text, 0, 0);
9,187,851✔
179
    }
9,187,851✔
180
    c.restore();
9,187,851✔
181
    d.width = w;
9,187,851✔
182
    d.height = h;
62,968,585✔
183
    d.xoff = x;
62,968,585✔
184
    d.yoff = y;
255,562,319✔
185
    d.x1 = w >> 1;
8,477,884✔
186
    d.y1 = h >> 1;
187
    d.x0 = -d.x1;
54,490,701✔
188
    d.y0 = -d.y1;
189
    d.hasText = true;
709,967✔
190
    x += w;
191
  }
192
  const pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
7,537✔
193
    sprite = [];
7,537✔
194
  while (--di >= 0) {
830✔
195
    d = data[di];
7,537✔
196
    if (!d.hasText) continue;
1,242✔
197
    const w = d.width,
7,537✔
198
      w32 = w >> 5;
1,118✔
199
    let h = d.y1 - d.y0;
7,537✔
200
    // Zero the buffer
1,595✔
201
    for (let i = 0; i < h * w32; i++) sprite[i] = 0;
202
    x = d.xoff;
203
    if (x == null) return;
709,967✔
204
    y = d.yoff;
205
    let seen = 0,
206
      seenRow = -1;
11,460✔
207
    for (let j = 0; j < h; j++) {
11,460✔
208
      for (let i = 0; i < w; i++) {
32,355,956✔
209
        const k = w32 * j + (i >> 5),
210
          m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
211
        sprite[k] |= m;
212
        seen |= m;
28✔
213
      }
28✔
214
      if (seen) seenRow = j;
28✔
215
      else {
28!
216
        d.y0++;
217
        h--;
28!
218
        j--;
219
        y++;
28✔
220
      }
28✔
221
    }
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,
28✔
232
    lx = tag.x - (w << 4),
233
    sx = lx & 0x7f,
234
    msx = 32 - sx,
235
    h = tag.y1 - tag.y0;
236
  let x = (tag.y + tag.y0) * sw + (lx >> 5),
929✔
237
    last;
929✔
238
  for (let j = 0; j < h; j++) {
929✔
239
    last = 0;
8,176,580✔
240
    for (let i = 0; i <= w; i++) {
929✔
241
      if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true;
242
    }
243
    x += sw;
929✔
244
  }
245
  return false;
246
}
10,033✔
247

248
function cloudBounds(bounds, d) {
249
  const b0 = bounds[0],
115,740✔
250
    b1 = bounds[1];
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;
5,818✔
253
  if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
5,818✔
254
  if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
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;
929✔
259
}
929✔
260

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

38,352✔
268
function rectangularSpiral(size) {
38,352✔
269
  const dy = 4,
38,352✔
270
    dx = (dy * size[0]) / size[1];
38,352✔
271
  let x = 0,
38,352✔
272
    y = 0;
38,352✔
273
  return function (t) {
38,352✔
274
    const sign = t < 0 ? -1 : 1;
38,352✔
275
    // See triangular numbers: T_n = n * (n + 1) / 2.
276
    switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
277
      case 0:
157,377✔
278
        x += dx;
279
        break;
929✔
280
      case 1:
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
  };
929✔
292
}
293

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

8,600✔
302
function cloudCanvas() {
7,789✔
303
  return document.createElement('canvas');
304
}
7,537✔
305

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

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

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

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

11,516✔
336
  cloud.start = function () {
11,516✔
337
    const [width, height] = size;
11,516✔
338
    const contextAndRatio = getContext(canvas()),
32,356,012✔
339
      board = cloud.board ? cloud.board : zeroArray((size[0] >> 5) * size[1]),
32,356,012✔
340
      n = words.length,
32,356,012✔
341
      tags = [],
2,916✔
342
      data = words
32,353,096✔
343
        .map(function (d, i, data) {
32,353,096✔
344
          d.text = text.call(this, d, i, data);
32,353,096✔
345
          d.font = font.call(this, d, i, data);
23,164,434✔
346
          d.style = fontStyle.call(this, d, i, data);
347
          d.weight = fontWeight.call(this, d, i, data);
9,188,662✔
348
          d.rotate = rotate.call(this, d, i, data);
710,778✔
349
          d.size = ~~fontSize.call(this, d, i, data);
8,600✔
350
          d.padding = padding.call(this, d, i, data);
8,600✔
351
          return d;
8,600✔
352
        })
666,246✔
353
        .sort(function (a, b) {
666,246✔
354
          return b.size - a.size;
3,611,453✔
355
        });
356
    let i = -1,
666,246✔
357
      bounds = !cloud.board
358
        ? null
8,600✔
359
        : [
8,600✔
360
            {
361
              x: 0,
362
              y: 0,
363
            },
2,916✔
364
            {
365
              x: width,
929✔
366
              y: height,
56✔
367
            },
56✔
368
          ];
369

56✔
370
    step();
28✔
371

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

929✔
401
    return cloud;
789✔
402
  };
403

929✔
404
  function getContext(canvas: HTMLCanvasElement) {
621✔
405
    canvas.width = canvas.height = 1;
406
    const ratio = Math.sqrt(canvas.getContext('2d')!.getImageData(0, 0, 1, 1).data.length >> 2);
929✔
407
    canvas.width = (cw << 5) / ratio;
649✔
408
    canvas.height = ch / ratio;
409

929✔
410
    const context = canvas.getContext('2d') as CanvasRenderingContext2D;
789✔
411
    context.fillStyle = context.strokeStyle = 'red';
412
    context.textAlign = 'center';
929✔
413
    return { context, ratio };
621✔
414
  }
415

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

428
    while ((dxdy = s((t += dt)))) {
429
      dx = ~~dxdy[0];
430
      dy = ~~dxdy[1];
431

432
      if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;
433

434
      tag.x = startX + dx;
435
      tag.y = startY + dy;
436

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

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

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

493
  cloud.timeInterval = function (_) {
494
    timeInterval = _ == null ? Infinity : _;
495
  };
496

497
  cloud.words = function (_) {
498
    words = _;
499
  };
500

501
  cloud.size = function (_) {
502
    size = [+_[0], +_[1]];
503
  };
504

505
  cloud.font = function (_) {
506
    font = functor(_);
507
  };
508

509
  cloud.fontWeight = function (_) {
510
    fontWeight = functor(_);
511
  };
512

513
  cloud.rotate = function (_) {
514
    rotate = functor(_);
515
  };
516

517
  cloud.spiral = function (_) {
518
    spiral = spirals[_] || _;
519
  };
520

521
  cloud.fontSize = function (_) {
522
    fontSize = functor(_);
523
  };
524

525
  cloud.padding = function (_) {
526
    padding = functor(_);
527
  };
528

529
  cloud.random = function (_) {
530
    random = functor(_);
531
  };
532

533
  return cloud;
534
}
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