d3.layout.cloud.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g=(g.d3||(g.d3 = {}));g=(g.layout||(g.layout = {}));g.cloud = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. // Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/
  3. // Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf
  4. var dispatch = require("d3-dispatch").dispatch;
  5. var cloudRadians = Math.PI / 180,
  6. cw = 1 << 11 >> 5,
  7. ch = 1 << 11;
  8. module.exports = function() {
  9. var size = [256, 256],
  10. text = cloudText,
  11. font = cloudFont,
  12. fontSize = cloudFontSize,
  13. fontStyle = cloudFontNormal,
  14. fontWeight = cloudFontNormal,
  15. rotate = cloudRotate,
  16. padding = cloudPadding,
  17. spiral = archimedeanSpiral,
  18. words = [],
  19. timeInterval = Infinity,
  20. event = dispatch("word", "end"),
  21. timer = null,
  22. random = Math.random,
  23. cloud = {},
  24. canvas = cloudCanvas;
  25. cloud.canvas = function(_) {
  26. return arguments.length ? (canvas = functor(_), cloud) : canvas;
  27. };
  28. cloud.start = function() {
  29. var contextAndRatio = getContext(canvas()),
  30. board = zeroArray((size[0] >> 5) * size[1]),
  31. bounds = null,
  32. n = words.length,
  33. i = -1,
  34. tags = [],
  35. data = words.map(function(d, i) {
  36. d.text = text.call(this, d, i);
  37. d.font = font.call(this, d, i);
  38. d.style = fontStyle.call(this, d, i);
  39. d.weight = fontWeight.call(this, d, i);
  40. d.rotate = rotate.call(this, d, i);
  41. d.size = ~~fontSize.call(this, d, i);
  42. d.padding = padding.call(this, d, i);
  43. return d;
  44. }).sort(function(a, b) { return b.size - a.size; });
  45. if (timer) clearInterval(timer);
  46. timer = setInterval(step, 0);
  47. step();
  48. return cloud;
  49. function step() {
  50. var start = Date.now();
  51. while (Date.now() - start < timeInterval && ++i < n && timer) {
  52. var d = data[i];
  53. d.x = (size[0] * (random() + .5)) >> 1;
  54. d.y = (size[1] * (random() + .5)) >> 1;
  55. cloudSprite(contextAndRatio, d, data, i);
  56. if (d.hasText && place(board, d, bounds)) {
  57. tags.push(d);
  58. event.call("word", cloud, d);
  59. if (bounds) cloudBounds(bounds, d);
  60. else bounds = [{x: d.x + d.x0, y: d.y + d.y0}, {x: d.x + d.x1, y: d.y + d.y1}];
  61. // Temporary hack
  62. d.x -= size[0] >> 1;
  63. d.y -= size[1] >> 1;
  64. }
  65. }
  66. if (i >= n) {
  67. cloud.stop();
  68. event.call("end", cloud, tags, bounds);
  69. }
  70. }
  71. }
  72. cloud.stop = function() {
  73. if (timer) {
  74. clearInterval(timer);
  75. timer = null;
  76. }
  77. return cloud;
  78. };
  79. function getContext(canvas) {
  80. canvas.width = canvas.height = 1;
  81. var ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2);
  82. canvas.width = (cw << 5) / ratio;
  83. canvas.height = ch / ratio;
  84. var context = canvas.getContext("2d");
  85. context.fillStyle = context.strokeStyle = "red";
  86. context.textAlign = "center";
  87. return {context: context, ratio: ratio};
  88. }
  89. function place(board, tag, bounds) {
  90. var perimeter = [{x: 0, y: 0}, {x: size[0], y: size[1]}],
  91. startX = tag.x,
  92. startY = tag.y,
  93. maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]),
  94. s = spiral(size),
  95. dt = random() < .5 ? 1 : -1,
  96. t = -dt,
  97. dxdy,
  98. dx,
  99. dy;
  100. while (dxdy = s(t += dt)) {
  101. dx = ~~dxdy[0];
  102. dy = ~~dxdy[1];
  103. if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break;
  104. tag.x = startX + dx;
  105. tag.y = startY + dy;
  106. if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 ||
  107. tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue;
  108. if (!bounds || !cloudCollide(tag, board, size[0])) {
  109. if (!bounds || collideRects(tag, bounds)) {
  110. var sprite = tag.sprite,
  111. w = tag.width >> 5,
  112. sw = size[0] >> 5,
  113. lx = tag.x - (w << 4),
  114. sx = lx & 0x7f,
  115. msx = 32 - sx,
  116. h = tag.y1 - tag.y0,
  117. x = (tag.y + tag.y0) * sw + (lx >> 5),
  118. last;
  119. for (var j = 0; j < h; j++) {
  120. last = 0;
  121. for (var i = 0; i <= w; i++) {
  122. board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
  123. }
  124. x += sw;
  125. }
  126. delete tag.sprite;
  127. return true;
  128. }
  129. }
  130. }
  131. return false;
  132. }
  133. cloud.timeInterval = function(_) {
  134. return arguments.length ? (timeInterval = _ == null ? Infinity : _, cloud) : timeInterval;
  135. };
  136. cloud.words = function(_) {
  137. return arguments.length ? (words = _, cloud) : words;
  138. };
  139. cloud.size = function(_) {
  140. return arguments.length ? (size = [+_[0], +_[1]], cloud) : size;
  141. };
  142. cloud.font = function(_) {
  143. return arguments.length ? (font = functor(_), cloud) : font;
  144. };
  145. cloud.fontStyle = function(_) {
  146. return arguments.length ? (fontStyle = functor(_), cloud) : fontStyle;
  147. };
  148. cloud.fontWeight = function(_) {
  149. return arguments.length ? (fontWeight = functor(_), cloud) : fontWeight;
  150. };
  151. cloud.rotate = function(_) {
  152. return arguments.length ? (rotate = functor(_), cloud) : rotate;
  153. };
  154. cloud.text = function(_) {
  155. return arguments.length ? (text = functor(_), cloud) : text;
  156. };
  157. cloud.spiral = function(_) {
  158. return arguments.length ? (spiral = spirals[_] || _, cloud) : spiral;
  159. };
  160. cloud.fontSize = function(_) {
  161. return arguments.length ? (fontSize = functor(_), cloud) : fontSize;
  162. };
  163. cloud.padding = function(_) {
  164. return arguments.length ? (padding = functor(_), cloud) : padding;
  165. };
  166. cloud.random = function(_) {
  167. return arguments.length ? (random = _, cloud) : random;
  168. };
  169. cloud.on = function() {
  170. var value = event.on.apply(event, arguments);
  171. return value === event ? cloud : value;
  172. };
  173. return cloud;
  174. };
  175. function cloudText(d) {
  176. return d.text;
  177. }
  178. function cloudFont() {
  179. return "serif";
  180. }
  181. function cloudFontNormal() {
  182. return "normal";
  183. }
  184. function cloudFontSize(d) {
  185. return Math.sqrt(d.value);
  186. }
  187. function cloudRotate() {
  188. return (~~(Math.random() * 6) - 3) * 30;
  189. }
  190. function cloudPadding() {
  191. return 1;
  192. }
  193. // Fetches a monochrome sprite bitmap for the specified text.
  194. // Load in batches for speed.
  195. function cloudSprite(contextAndRatio, d, data, di) {
  196. if (d.sprite) return;
  197. var c = contextAndRatio.context,
  198. ratio = contextAndRatio.ratio;
  199. c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
  200. var x = 0,
  201. y = 0,
  202. maxh = 0,
  203. n = data.length;
  204. --di;
  205. while (++di < n) {
  206. d = data[di];
  207. c.save();
  208. c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font;
  209. var w = c.measureText(d.text + "m").width * ratio,
  210. h = d.size << 1;
  211. if (d.rotate) {
  212. var sr = Math.sin(d.rotate * cloudRadians),
  213. cr = Math.cos(d.rotate * cloudRadians),
  214. wcr = w * cr,
  215. wsr = w * sr,
  216. hcr = h * cr,
  217. hsr = h * sr;
  218. w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5;
  219. h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
  220. } else {
  221. w = (w + 0x1f) >> 5 << 5;
  222. }
  223. if (h > maxh) maxh = h;
  224. if (x + w >= (cw << 5)) {
  225. x = 0;
  226. y += maxh;
  227. maxh = 0;
  228. }
  229. if (y + h >= ch) break;
  230. c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
  231. if (d.rotate) c.rotate(d.rotate * cloudRadians);
  232. c.fillText(d.text, 0, 0);
  233. if (d.padding) c.lineWidth = 2 * d.padding, c.strokeText(d.text, 0, 0);
  234. c.restore();
  235. d.width = w;
  236. d.height = h;
  237. d.xoff = x;
  238. d.yoff = y;
  239. d.x1 = w >> 1;
  240. d.y1 = h >> 1;
  241. d.x0 = -d.x1;
  242. d.y0 = -d.y1;
  243. d.hasText = true;
  244. x += w;
  245. }
  246. var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
  247. sprite = [];
  248. while (--di >= 0) {
  249. d = data[di];
  250. if (!d.hasText) continue;
  251. var w = d.width,
  252. w32 = w >> 5,
  253. h = d.y1 - d.y0;
  254. // Zero the buffer
  255. for (var i = 0; i < h * w32; i++) sprite[i] = 0;
  256. x = d.xoff;
  257. if (x == null) return;
  258. y = d.yoff;
  259. var seen = 0,
  260. seenRow = -1;
  261. for (var j = 0; j < h; j++) {
  262. for (var i = 0; i < w; i++) {
  263. var k = w32 * j + (i >> 5),
  264. m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
  265. sprite[k] |= m;
  266. seen |= m;
  267. }
  268. if (seen) seenRow = j;
  269. else {
  270. d.y0++;
  271. h--;
  272. j--;
  273. y++;
  274. }
  275. }
  276. d.y1 = d.y0 + seenRow;
  277. d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
  278. }
  279. }
  280. // Use mask-based collision detection.
  281. function cloudCollide(tag, board, sw) {
  282. sw >>= 5;
  283. var sprite = tag.sprite,
  284. w = tag.width >> 5,
  285. lx = tag.x - (w << 4),
  286. sx = lx & 0x7f,
  287. msx = 32 - sx,
  288. h = tag.y1 - tag.y0,
  289. x = (tag.y + tag.y0) * sw + (lx >> 5),
  290. last;
  291. for (var j = 0; j < h; j++) {
  292. last = 0;
  293. for (var i = 0; i <= w; i++) {
  294. if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0))
  295. & board[x + i]) return true;
  296. }
  297. x += sw;
  298. }
  299. return false;
  300. }
  301. function cloudBounds(bounds, d) {
  302. var b0 = bounds[0],
  303. b1 = bounds[1];
  304. if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
  305. if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
  306. if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
  307. if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
  308. }
  309. function collideRects(a, b) {
  310. 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;
  311. }
  312. function archimedeanSpiral(size) {
  313. var e = size[0] / size[1];
  314. return function(t) {
  315. return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];
  316. };
  317. }
  318. function rectangularSpiral(size) {
  319. var dy = 4,
  320. dx = dy * size[0] / size[1],
  321. x = 0,
  322. y = 0;
  323. return function(t) {
  324. var sign = t < 0 ? -1 : 1;
  325. // See triangular numbers: T_n = n * (n + 1) / 2.
  326. switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
  327. case 0: x += dx; break;
  328. case 1: y += dy; break;
  329. case 2: x -= dx; break;
  330. default: y -= dy; break;
  331. }
  332. return [x, y];
  333. };
  334. }
  335. function zeroArray(n) {
  336. var a = [],
  337. i = -1;
  338. while (++i < n) a[i] = 0;
  339. return a;
  340. }
  341. function cloudCanvas() {
  342. return document.createElement("canvas");
  343. }
  344. function functor(d) {
  345. return typeof d === "function" ? d : function() { return d; };
  346. }
  347. var spirals = {
  348. archimedean: archimedeanSpiral,
  349. rectangular: rectangularSpiral
  350. };
  351. },{"d3-dispatch":2}],2:[function(require,module,exports){
  352. // https://d3js.org/d3-dispatch/ Version 1.0.3. Copyright 2017 Mike Bostock.
  353. (function (global, factory) {
  354. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  355. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  356. (factory((global.d3 = global.d3 || {})));
  357. }(this, (function (exports) { 'use strict';
  358. var noop = {value: function() {}};
  359. function dispatch() {
  360. for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
  361. if (!(t = arguments[i] + "") || (t in _)) throw new Error("illegal type: " + t);
  362. _[t] = [];
  363. }
  364. return new Dispatch(_);
  365. }
  366. function Dispatch(_) {
  367. this._ = _;
  368. }
  369. function parseTypenames(typenames, types) {
  370. return typenames.trim().split(/^|\s+/).map(function(t) {
  371. var name = "", i = t.indexOf(".");
  372. if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
  373. if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
  374. return {type: t, name: name};
  375. });
  376. }
  377. Dispatch.prototype = dispatch.prototype = {
  378. constructor: Dispatch,
  379. on: function(typename, callback) {
  380. var _ = this._,
  381. T = parseTypenames(typename + "", _),
  382. t,
  383. i = -1,
  384. n = T.length;
  385. // If no callback was specified, return the callback of the given type and name.
  386. if (arguments.length < 2) {
  387. while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
  388. return;
  389. }
  390. // If a type was specified, set the callback for the given type and name.
  391. // Otherwise, if a null callback was specified, remove callbacks of the given name.
  392. if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
  393. while (++i < n) {
  394. if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
  395. else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
  396. }
  397. return this;
  398. },
  399. copy: function() {
  400. var copy = {}, _ = this._;
  401. for (var t in _) copy[t] = _[t].slice();
  402. return new Dispatch(copy);
  403. },
  404. call: function(type, that) {
  405. if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
  406. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  407. for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  408. },
  409. apply: function(type, that, args) {
  410. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  411. for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  412. }
  413. };
  414. function get(type, name) {
  415. for (var i = 0, n = type.length, c; i < n; ++i) {
  416. if ((c = type[i]).name === name) {
  417. return c.value;
  418. }
  419. }
  420. }
  421. function set(type, name, callback) {
  422. for (var i = 0, n = type.length; i < n; ++i) {
  423. if (type[i].name === name) {
  424. type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
  425. break;
  426. }
  427. }
  428. if (callback != null) type.push({name: name, value: callback});
  429. return type;
  430. }
  431. exports.dispatch = dispatch;
  432. Object.defineProperty(exports, '__esModule', { value: true });
  433. })));
  434. },{}]},{},[1])(1)
  435. });