d3.layout.cloud.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. // TODO only check for collisions within current bounds.
  109. if (!bounds || !cloudCollide(tag, board, size[0])) {
  110. if (!bounds || collideRects(tag, bounds)) {
  111. var sprite = tag.sprite,
  112. w = tag.width >> 5,
  113. sw = size[0] >> 5,
  114. lx = tag.x - (w << 4),
  115. sx = lx & 0x7f,
  116. msx = 32 - sx,
  117. h = tag.y1 - tag.y0,
  118. x = (tag.y + tag.y0) * sw + (lx >> 5),
  119. last;
  120. for (var j = 0; j < h; j++) {
  121. last = 0;
  122. for (var i = 0; i <= w; i++) {
  123. board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0);
  124. }
  125. x += sw;
  126. }
  127. delete tag.sprite;
  128. return true;
  129. }
  130. }
  131. }
  132. return false;
  133. }
  134. cloud.timeInterval = function(_) {
  135. return arguments.length ? (timeInterval = _ == null ? Infinity : _, cloud) : timeInterval;
  136. };
  137. cloud.words = function(_) {
  138. return arguments.length ? (words = _, cloud) : words;
  139. };
  140. cloud.size = function(_) {
  141. return arguments.length ? (size = [+_[0], +_[1]], cloud) : size;
  142. };
  143. cloud.font = function(_) {
  144. return arguments.length ? (font = functor(_), cloud) : font;
  145. };
  146. cloud.fontStyle = function(_) {
  147. return arguments.length ? (fontStyle = functor(_), cloud) : fontStyle;
  148. };
  149. cloud.fontWeight = function(_) {
  150. return arguments.length ? (fontWeight = functor(_), cloud) : fontWeight;
  151. };
  152. cloud.rotate = function(_) {
  153. return arguments.length ? (rotate = functor(_), cloud) : rotate;
  154. };
  155. cloud.text = function(_) {
  156. return arguments.length ? (text = functor(_), cloud) : text;
  157. };
  158. cloud.spiral = function(_) {
  159. return arguments.length ? (spiral = spirals[_] || _, cloud) : spiral;
  160. };
  161. cloud.fontSize = function(_) {
  162. return arguments.length ? (fontSize = functor(_), cloud) : fontSize;
  163. };
  164. cloud.padding = function(_) {
  165. return arguments.length ? (padding = functor(_), cloud) : padding;
  166. };
  167. cloud.random = function(_) {
  168. return arguments.length ? (random = _, cloud) : random;
  169. };
  170. cloud.on = function() {
  171. var value = event.on.apply(event, arguments);
  172. return value === event ? cloud : value;
  173. };
  174. return cloud;
  175. };
  176. function cloudText(d) {
  177. return d.text;
  178. }
  179. function cloudFont() {
  180. return "serif";
  181. }
  182. function cloudFontNormal() {
  183. return "normal";
  184. }
  185. function cloudFontSize(d) {
  186. return Math.sqrt(d.value);
  187. }
  188. function cloudRotate() {
  189. return (~~(Math.random() * 6) - 3) * 30;
  190. }
  191. function cloudPadding() {
  192. return 1;
  193. }
  194. // Fetches a monochrome sprite bitmap for the specified text.
  195. // Load in batches for speed.
  196. function cloudSprite(contextAndRatio, d, data, di) {
  197. if (d.sprite) return;
  198. var c = contextAndRatio.context,
  199. ratio = contextAndRatio.ratio;
  200. c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio);
  201. var x = 0,
  202. y = 0,
  203. maxh = 0,
  204. n = data.length;
  205. --di;
  206. while (++di < n) {
  207. d = data[di];
  208. c.save();
  209. c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font;
  210. var w = c.measureText(d.text + "m").width * ratio,
  211. h = d.size << 1;
  212. if (d.rotate) {
  213. var sr = Math.sin(d.rotate * cloudRadians),
  214. cr = Math.cos(d.rotate * cloudRadians),
  215. wcr = w * cr,
  216. wsr = w * sr,
  217. hcr = h * cr,
  218. hsr = h * sr;
  219. w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5;
  220. h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr));
  221. } else {
  222. w = (w + 0x1f) >> 5 << 5;
  223. }
  224. if (h > maxh) maxh = h;
  225. if (x + w >= (cw << 5)) {
  226. x = 0;
  227. y += maxh;
  228. maxh = 0;
  229. }
  230. if (y + h >= ch) break;
  231. c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio);
  232. if (d.rotate) c.rotate(d.rotate * cloudRadians);
  233. c.fillText(d.text, 0, 0);
  234. if (d.padding) c.lineWidth = 2 * d.padding, c.strokeText(d.text, 0, 0);
  235. c.restore();
  236. d.width = w;
  237. d.height = h;
  238. d.xoff = x;
  239. d.yoff = y;
  240. d.x1 = w >> 1;
  241. d.y1 = h >> 1;
  242. d.x0 = -d.x1;
  243. d.y0 = -d.y1;
  244. d.hasText = true;
  245. x += w;
  246. }
  247. var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data,
  248. sprite = [];
  249. while (--di >= 0) {
  250. d = data[di];
  251. if (!d.hasText) continue;
  252. var w = d.width,
  253. w32 = w >> 5,
  254. h = d.y1 - d.y0;
  255. // Zero the buffer
  256. for (var i = 0; i < h * w32; i++) sprite[i] = 0;
  257. x = d.xoff;
  258. if (x == null) return;
  259. y = d.yoff;
  260. var seen = 0,
  261. seenRow = -1;
  262. for (var j = 0; j < h; j++) {
  263. for (var i = 0; i < w; i++) {
  264. var k = w32 * j + (i >> 5),
  265. m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0;
  266. sprite[k] |= m;
  267. seen |= m;
  268. }
  269. if (seen) seenRow = j;
  270. else {
  271. d.y0++;
  272. h--;
  273. j--;
  274. y++;
  275. }
  276. }
  277. d.y1 = d.y0 + seenRow;
  278. d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32);
  279. }
  280. }
  281. // Use mask-based collision detection.
  282. function cloudCollide(tag, board, sw) {
  283. sw >>= 5;
  284. var sprite = tag.sprite,
  285. w = tag.width >> 5,
  286. lx = tag.x - (w << 4),
  287. sx = lx & 0x7f,
  288. msx = 32 - sx,
  289. h = tag.y1 - tag.y0,
  290. x = (tag.y + tag.y0) * sw + (lx >> 5),
  291. last;
  292. for (var j = 0; j < h; j++) {
  293. last = 0;
  294. for (var i = 0; i <= w; i++) {
  295. if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0))
  296. & board[x + i]) return true;
  297. }
  298. x += sw;
  299. }
  300. return false;
  301. }
  302. function cloudBounds(bounds, d) {
  303. var b0 = bounds[0],
  304. b1 = bounds[1];
  305. if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0;
  306. if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0;
  307. if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1;
  308. if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1;
  309. }
  310. function collideRects(a, b) {
  311. 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;
  312. }
  313. function archimedeanSpiral(size) {
  314. var e = size[0] / size[1];
  315. return function(t) {
  316. return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)];
  317. };
  318. }
  319. function rectangularSpiral(size) {
  320. var dy = 4,
  321. dx = dy * size[0] / size[1],
  322. x = 0,
  323. y = 0;
  324. return function(t) {
  325. var sign = t < 0 ? -1 : 1;
  326. // See triangular numbers: T_n = n * (n + 1) / 2.
  327. switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) {
  328. case 0: x += dx; break;
  329. case 1: y += dy; break;
  330. case 2: x -= dx; break;
  331. default: y -= dy; break;
  332. }
  333. return [x, y];
  334. };
  335. }
  336. // TODO reuse arrays?
  337. function zeroArray(n) {
  338. var a = [],
  339. i = -1;
  340. while (++i < n) a[i] = 0;
  341. return a;
  342. }
  343. function cloudCanvas() {
  344. return document.createElement("canvas");
  345. }
  346. function functor(d) {
  347. return typeof d === "function" ? d : function() { return d; };
  348. }
  349. var spirals = {
  350. archimedean: archimedeanSpiral,
  351. rectangular: rectangularSpiral
  352. };
  353. },{"d3-dispatch":2}],2:[function(require,module,exports){
  354. // https://d3js.org/d3-dispatch/ Version 1.0.3. Copyright 2017 Mike Bostock.
  355. (function (global, factory) {
  356. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  357. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  358. (factory((global.d3 = global.d3 || {})));
  359. }(this, (function (exports) { 'use strict';
  360. var noop = {value: function() {}};
  361. function dispatch() {
  362. for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {
  363. if (!(t = arguments[i] + "") || (t in _)) throw new Error("illegal type: " + t);
  364. _[t] = [];
  365. }
  366. return new Dispatch(_);
  367. }
  368. function Dispatch(_) {
  369. this._ = _;
  370. }
  371. function parseTypenames(typenames, types) {
  372. return typenames.trim().split(/^|\s+/).map(function(t) {
  373. var name = "", i = t.indexOf(".");
  374. if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
  375. if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t);
  376. return {type: t, name: name};
  377. });
  378. }
  379. Dispatch.prototype = dispatch.prototype = {
  380. constructor: Dispatch,
  381. on: function(typename, callback) {
  382. var _ = this._,
  383. T = parseTypenames(typename + "", _),
  384. t,
  385. i = -1,
  386. n = T.length;
  387. // If no callback was specified, return the callback of the given type and name.
  388. if (arguments.length < 2) {
  389. while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;
  390. return;
  391. }
  392. // If a type was specified, set the callback for the given type and name.
  393. // Otherwise, if a null callback was specified, remove callbacks of the given name.
  394. if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback);
  395. while (++i < n) {
  396. if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);
  397. else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);
  398. }
  399. return this;
  400. },
  401. copy: function() {
  402. var copy = {}, _ = this._;
  403. for (var t in _) copy[t] = _[t].slice();
  404. return new Dispatch(copy);
  405. },
  406. call: function(type, that) {
  407. if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];
  408. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  409. for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  410. },
  411. apply: function(type, that, args) {
  412. if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type);
  413. for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);
  414. }
  415. };
  416. function get(type, name) {
  417. for (var i = 0, n = type.length, c; i < n; ++i) {
  418. if ((c = type[i]).name === name) {
  419. return c.value;
  420. }
  421. }
  422. }
  423. function set(type, name, callback) {
  424. for (var i = 0, n = type.length; i < n; ++i) {
  425. if (type[i].name === name) {
  426. type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
  427. break;
  428. }
  429. }
  430. if (callback != null) type.push({name: name, value: callback});
  431. return type;
  432. }
  433. exports.dispatch = dispatch;
  434. Object.defineProperty(exports, '__esModule', { value: true });
  435. })));
  436. },{}]},{},[1])(1)
  437. });