
1.先上代码,
使用方法 导入 wordcloud2.js
javascript
<div style="width:500px;height:300px" ref="container "></div>
javascript
import WordCloud from '@/utils/wordcloud2';
const container = ref(null)
//list是二维数组
let list = [
['数据',1],
['数据1',2],
['数据2',3],
]
try {
WordCloud(container.value, {
list: list,
gridSize: 6,
weightFactor: function (size) {
// 验证 size 是否为有效数字
if (!size || typeof size !== 'number' || isNaN(size) || size <= 0) {
return baseWeightFactor;
}
// 根据权重计算字体大小
const fontSize = Math.sqrt(size) * baseWeightFactor;
// 如果字体大小小于8,返回基础系数作为最小值
if (fontSize < 8) {
return baseWeightFactor;
}
// 限制最大值
return Math.min(fontSize, maxFontSize);
},
minFontSize: 14, // 最小字体
rotationSteps: 0,
rotateRatio: 0.5,
rotationRange: [0, 45],
drawOutOfBound: false, // 关键:不溢出画布
fontFamily: 'Microsoft YaHei',
shrinkToFit: true, // 是否自动缩小字体以适应容器
shape: 'circle', // 词云形状 cardioid心型 triangle直立三角形 triangle-forward三角形(前倾 / 右向) pentagon五边形 star星形(五角星)
ellipticity: 0.7, // 扁一点,像云朵
});
} catch (e) {
console.error('WordCloud 初始化失败:', e);
}
/*如果自定义任意形状(SVG path)
不满足内置形状时,可用 SVG 路径字符串 实现任意轮廓(动物、logo、文字等)
shape: 'path://M100 200...' // 粘贴你的 SVG <path d="...">
*/
wordcloud2.js 直接拷贝
在原来js基础上改成了ES module方式链接
javascript
(function (t) {
if (!window.setImmediate) {
window.setImmediate = function (t) {
return window.setTimeout(t, 0);
};
window.clearImmediate = function (t) {
window.clearTimeout(t);
};
}
function e(v, t) {
if (V) {
var e,
i = Math.floor(Math.random() * Date.now()),
T =
((v = Array.isArray(v) ? v : [v]).forEach(function (t, e) {
if ('string' == typeof t) {
if (((v[e] = document.getElementById(t)), !v[e])) throw new Error('The element id specified is not found.');
} else if (!t.tagName && !t.appendChild) throw new Error('You must pass valid HTML elements, or ID of the element.');
}),
{
list: [],
fontFamily: '"Trebuchet MS", "Heiti TC", "微軟正黑體", "Arial Unicode MS", "Droid Fallback Sans", sans-serif',
fontWeight: 'normal',
color: 'random-dark',
minSize: 0,
weightFactor: 1,
clearCanvas: !0,
backgroundColor: '#fff',
gridSize: 8,
drawOutOfBound: !1,
shrinkToFit: !1,
origin: null,
drawMask: !1,
maskColor: 'rgba(255,0,0,0.3)',
maskGapWidth: 0.3,
wait: 0,
abortThreshold: 0,
abort: function () {},
minRotation: -Math.PI / 2,
maxRotation: Math.PI / 2,
rotationSteps: 0,
shuffle: !0,
rotateRatio: 0.1,
shape: 'circle',
ellipticity: 0.65,
classes: null,
hover: null,
click: null,
});
if (t) for (var o in t) o in T && (T[o] = t[o]);
if (
('function' != typeof T.weightFactor &&
((e = T.weightFactor),
(T.weightFactor = function (t) {
return t * e;
})),
'function' != typeof T.shape)
)
switch (T.shape) {
case 'circle':
default:
T.shape = 'circle';
break;
case 'cardioid':
T.shape = function (t) {
return 1 - Math.sin(t);
};
break;
case 'diamond':
T.shape = function (t) {
t %= (2 * Math.PI) / 4;
return 1 / (Math.cos(t) + Math.sin(t));
};
break;
case 'square':
T.shape = function (t) {
return Math.min(1 / Math.abs(Math.cos(t)), 1 / Math.abs(Math.sin(t)));
};
break;
case 'triangle-forward':
T.shape = function (t) {
t %= (2 * Math.PI) / 3;
return 1 / (Math.cos(t) + Math.sqrt(3) * Math.sin(t));
};
break;
case 'triangle':
case 'triangle-upright':
T.shape = function (t) {
t = (t + (3 * Math.PI) / 2) % ((2 * Math.PI) / 3);
return 1 / (Math.cos(t) + Math.sqrt(3) * Math.sin(t));
};
break;
case 'pentagon':
T.shape = function (t) {
t = (t + 0.955) % ((2 * Math.PI) / 5);
return 1 / (Math.cos(t) + 0.726543 * Math.sin(t));
};
break;
case 'star':
T.shape = function (t) {
var e = (t + 0.955) % ((2 * Math.PI) / 10);
return 0 <= ((t + 0.955) % ((2 * Math.PI) / 5)) - (2 * Math.PI) / 10
? 1 / (Math.cos((2 * Math.PI) / 10 - e) + 3.07768 * Math.sin((2 * Math.PI) / 10 - e))
: 1 / (Math.cos(e) + 3.07768 * Math.sin(e));
};
}
T.gridSize = Math.max(Math.floor(T.gridSize), 4);
var g,
M,
p,
r,
x,
a,
n,
y,
I = T.gridSize,
L = I - T.maskGapWidth,
s = Math.abs(T.maxRotation - T.minRotation),
l = Math.abs(Math.floor(T.rotationSteps)),
d = Math.min(T.maxRotation, T.minRotation);
switch (T.color) {
case 'random-dark':
n = function () {
return Q(10, 50);
};
break;
case 'random-light':
n = function () {
return Q(50, 90);
};
break;
default:
'function' == typeof T.color && (n = T.color);
}
'function' == typeof T.fontWeight && (y = T.fontWeight);
var f,
c,
h,
b = null,
k = ('function' == typeof T.classes && (b = T.classes), !1),
C = [],
D = function (t) {
var e = t.currentTarget,
i = e.getBoundingClientRect(),
t = t.touches ? ((o = t.touches[0].clientX), t.touches[0].clientY) : ((o = t.clientX), t.clientY),
o = o - i.left,
t = t - i.top,
o = Math.floor(((o < 0 ? 0 : o) * (e.width / i.width || 1)) / I),
t = Math.floor((t * (e.height / i.height || 1)) / I);
return C[o] ? C[o][t] : null;
},
B = function (t) {
var e = D(t);
f !== e && ((f = e) ? T.hover(e.item, e.dimension, t) : T.hover(void 0, void 0, t));
},
H = function (t) {
var e = D(t);
e && (T.click(e.item, e.dimension, t), t.preventDefault());
},
u = [],
X = function (t) {
if (u[t]) return u[t];
var e = 8 * t,
i = e,
o = [];
for (0 === t && o.push([r[0], r[1], 0]); i--; ) {
var a = 1;
('circle' !== T.shape && (a = T.shape((i / e) * 2 * Math.PI)),
o.push([r[0] + t * a * Math.cos((-i / e) * 2 * Math.PI), r[1] + t * a * Math.sin((-i / e) * 2 * Math.PI) * T.ellipticity, (i / e) * 2 * Math.PI]));
}
return (u[t] = o);
},
S = function () {
return 0 < T.abortThreshold && new Date().getTime() - a > T.abortThreshold;
},
Y = function () {
return 0 === T.rotateRatio || Math.random() > T.rotateRatio ? 0 : 0 === s ? d : 0 < l ? d + (Math.floor(Math.random() * l) * s) / (l - 1) : d + Math.random() * s;
},
q = function (t, e, i, o) {
var a = T.weightFactor(e);
if (a <= T.minSize) return !1;
var r = 1,
o =
(a < Z &&
(r = (function () {
for (var t = 2; t * a < Z; ) t += 2;
return t;
})()),
(e = y ? y(t, e, a, o) : T.fontWeight),
document.createElement('canvas')),
n = o.getContext('2d', { willReadFrequently: !0 }),
s = ((n.font = e + ' ' + (a * r).toString(10) + 'px ' + T.fontFamily), n.measureText(t).width / r),
l = Math.max(a * r, n.measureText('m').width, n.measureText('W').width) / r,
d = s + 2 * l,
f = 3 * l,
c = Math.ceil(d / I),
h = Math.ceil(f / I),
d = c * I,
f = h * I,
c = -s / 2,
h = 0.4 * -l,
u = Math.ceil((d * Math.abs(Math.sin(i)) + f * Math.abs(Math.cos(i))) / I),
d = Math.ceil((d * Math.abs(Math.cos(i)) + f * Math.abs(Math.sin(i))) / I),
m = d * I,
f = u * I,
w =
(o.setAttribute('width', m),
o.setAttribute('height', f),
n.scale(1 / r, 1 / r),
n.translate((m * r) / 2, (f * r) / 2),
n.rotate(-i),
(n.font = e + ' ' + (a * r).toString(10) + 'px ' + T.fontFamily),
(n.fillStyle = '#000'),
(n.textBaseline = 'middle'),
n.fillText(t, c * r, (h + 0.5 * a) * r),
n.getImageData(0, 0, m, f).data);
if (S()) return !1;
for (var g, v, M, p = [], x = d, b = [u / 2, d / 2, u / 2, d / 2]; x--; )
for (g = u; g--; ) {
M = I;
t: for (; M--; )
for (v = I; v--; )
if (w[4 * ((g * I + M) * m + (x * I + v)) + 3]) {
(p.push([x, g]), x < b[3] && (b[3] = x), x > b[1] && (b[1] = x), g < b[0] && (b[0] = g), g > b[2] && (b[2] = g));
break t;
}
}
return { mu: r, occupied: p, bounds: b, gw: d, gh: u, fillTextOffsetX: c, fillTextOffsetY: h, fillTextWidth: s, fillTextHeight: l, fontSize: a };
},
G = function (t, e, i, o, a) {
for (var r = a.length; r--; ) {
var n = t + a[r][0],
s = e + a[r][1];
if (M <= n || p <= s || n < 0 || s < 0) {
if (T.drawOutOfBound) continue;
return !1;
}
if (!g[n][s]) return !1;
}
return !0;
},
N = function (s, l, d, f, t, e, i, c, h, o) {
var u = d.fontSize,
m = n ? n(f, t, u, e, i, o) : T.color,
w = y ? y(f, t, u, o) : T.fontWeight,
g = b ? b(f, t, u, o) : T.classes;
v.forEach(function (t) {
if (t.getContext) {
var e = t.getContext('2d'),
i = d.mu;
(e.save(),
e.scale(1 / i, 1 / i),
(e.font = w + ' ' + (u * i).toString(10) + 'px ' + T.fontFamily),
(e.fillStyle = m),
e.translate((s + d.gw / 2) * I * i, (l + d.gh / 2) * I * i),
0 !== c && e.rotate(-c),
(e.textBaseline = 'middle'),
e.fillText(f, d.fillTextOffsetX * i, (d.fillTextOffsetY + 0.5 * u) * i),
e.restore());
} else {
var o,
a = document.createElement('span'),
i = '',
i = 'rotate(' + (-c / Math.PI) * 180 + 'deg) ',
r =
(1 !== d.mu && (i += 'translateX(-' + d.fillTextWidth / 4 + 'px) scale(' + 1 / d.mu + ')'),
{
position: 'absolute',
display: 'block',
font: w + ' ' + u * d.mu + 'px ' + T.fontFamily,
left: (s + d.gw / 2) * I + d.fillTextOffsetX + 'px',
top: (l + d.gh / 2) * I + d.fillTextOffsetY + 'px',
width: d.fillTextWidth + 'px',
height: d.fillTextHeight + 'px',
lineHeight: u + 'px',
whiteSpace: 'nowrap',
transform: i,
webkitTransform: i,
msTransform: i,
transformOrigin: '50% 40%',
webkitTransformOrigin: '50% 40%',
msTransformOrigin: '50% 40%',
});
for (o in (m && (r.color = m), (a.textContent = f), r)) a.style[o] = r[o];
if (h) for (var n in h) a.setAttribute(n, h[n]);
(g && (a.className += g), t.appendChild(a));
}
});
},
U = function (t, e, i, o, a, r) {
for (
var n,
s,
l,
d,
f,
c = a.occupied,
h = T.drawMask,
u =
(h && ((n = v[0].getContext('2d')).save(), (n.fillStyle = T.maskColor)),
k && (s = { x: (t + (a = a.bounds)[3]) * I, y: (e + a[0]) * I, w: (a[1] - a[3] + 1) * I, h: (a[2] - a[0] + 1) * I }),
c.length);
u--;
) {
var m = t + c[u][0],
w = e + c[u][1];
M <= m ||
p <= w ||
m < 0 ||
w < 0 ||
((w = w),
(l = h),
(d = s),
(f = r),
M <= (m = m) || p <= w || m < 0 || w < 0 || ((g[m][w] = !1), l && v[0].getContext('2d').fillRect(m * I, w * I, L, L), k && (C[m][w] = { item: f, dimension: d })));
}
h && n.restore();
},
j = function t(r) {
Array.isArray(r) ? ((n = r[0]), (s = r[1])) : ((n = r.word), (s = r.weight), (l = r.attributes));
var n,
s,
l,
d = Y(),
f = ((e = r), Array.isArray(e) ? ((e = e.slice()).splice(0, 2), e) : []),
c = q(n, s, d, f);
if (!c) return !1;
if (S()) return !1;
if (!T.drawOutOfBound && !T.shrinkToFit) {
var e = c.bounds;
if (e[1] - e[3] + 1 > M || e[2] - e[0] + 1 > p) return !1;
}
for (
var h = x + 1,
i = function (t) {
var e = Math.floor(t[0] - c.gw / 2),
i = Math.floor(t[1] - c.gh / 2),
o = c.gw,
a = c.gh;
return !!G(e, i, o, a, c.occupied) && (N(e, i, c, n, s, x - h, t[2], d, l, f), U(e, i, o, a, c, r), !0);
};
h--;
) {
var o = X(x - h);
if (T.shuffle) {
((o = [].concat(o)), (w = u = a = m = void 0));
for (var a, u, m = o, w = m.length; w; ) ((a = Math.floor(Math.random() * w)), (u = m[--w]), (m[w] = m[a]), (m[a] = u));
}
if (o.some(i)) return !0;
}
return !!T.shrinkToFit && (Array.isArray(r) ? (r[1] = (3 * r[1]) / 4) : (r.weight = (3 * r.weight) / 4), t(r));
},
m = function (i, t, o) {
if (t)
return !v.some(function (t) {
var e = new CustomEvent(i, { detail: o || {} });
return !t.dispatchEvent(e);
}, this);
v.forEach(function (t) {
var e = new CustomEvent(i, { detail: o || {} });
t.dispatchEvent(e);
}, this);
},
w = v[0];
if (
((p = w.getContext ? ((M = Math.ceil(w.width / I)), Math.ceil(w.height / I)) : ((P = w.getBoundingClientRect()), (M = Math.ceil(P.width / I)), Math.ceil(P.height / I))),
m('wordcloudstart', !0))
) {
if (((r = T.origin ? [T.origin[0] / I, T.origin[1] / I] : [M / 2, p / 2]), (x = Math.floor(Math.sqrt(M * M + p * p))), (g = []), !w.getContext || T.clearCanvas))
for (
v.forEach(function (t) {
var e;
t.getContext
? (((e = t.getContext('2d')).fillStyle = T.backgroundColor), e.clearRect(0, 0, M * (I + 1), p * (I + 1)), e.fillRect(0, 0, M * (I + 1), p * (I + 1)))
: ((t.textContent = ''), (t.style.backgroundColor = T.backgroundColor), (t.style.position = 'relative'));
}),
R = M;
R--;
)
for (g[R] = [], c = p; c--; ) g[R][c] = !0;
else {
for (
var E,
F,
P = document.createElement('canvas').getContext('2d'),
J = ((P.fillStyle = T.backgroundColor), P.fillRect(0, 0, 1, 1), P.getImageData(0, 0, 1, 1).data),
K = w.getContext('2d').getImageData(0, 0, M * I, p * I).data,
R = M;
R--;
)
for (g[R] = [], c = p; c--; ) {
F = I;
t: for (; F--; )
for (E = I; E--; )
for (O = 4; O--; )
if (K[4 * ((c * I + F) * M * I + (R * I + E)) + O] !== J[O]) {
g[R][c] = !1;
break t;
}
!1 !== g[R][c] && (g[R][c] = !0);
}
K = P = J = void 0;
}
if (T.hover || T.click) {
for (k = !0, R = M + 1; R--; ) C[R] = [];
(T.hover && w.addEventListener('mousemove', B),
T.click && (w.addEventListener('click', H), (w.style.webkitTapHighlightColor = 'rgba(0, 0, 0, 0)')),
w.addEventListener('wordcloudstart', function t() {
(w.removeEventListener('wordcloudstart', t), w.removeEventListener('mousemove', B), w.removeEventListener('click', H), (f = void 0));
}));
}
var O = 0,
A = 0 !== T.wait ? ((h = window.setTimeout), window.clearTimeout) : ((h = window.setImmediate), window.clearImmediate),
z = function (e, i) {
v.forEach(function (t) {
t.removeEventListener(e, i);
}, this);
},
W = function t() {
(z('wordcloudstart', t), A($[i]));
};
(!(function (e, i) {
v.forEach(function (t) {
t.addEventListener(e, i);
}, this);
})('wordcloudstart', W),
($[i] = h(function t() {
if (O >= T.list.length) return (A($[i]), m('wordcloudstop', !1), z('wordcloudstart', W), void delete $[i]);
a = new Date().getTime();
var e = j(T.list[O]),
e = !m('wordclouddrawn', !0, { item: T.list[O], drawn: e });
if (S() || e) return (A($[i]), T.abort(), m('wordcloudabort', !1), m('wordcloudstop', !1), z('wordcloudstart', W), void delete $[i]);
(O++, ($[i] = h(t, T.wait)));
}, T.wait)));
}
}
function Q(t, e) {
return 'hsl(' + (360 * Math.random()).toFixed() + ',' + (30 * Math.random() + 70).toFixed() + '%,' + (Math.random() * (e - t) + t).toFixed() + '%)';
}
}
var V = (function () {
var t = document.createElement('canvas');
if (!t || !t.getContext) return !1;
t = t.getContext('2d');
return !!t && !!t.getImageData && !!t.fillText && !!Array.prototype.some && !!Array.prototype.push;
})(),
Z = (function () {
if (V) {
for (var t, e, i = document.createElement('canvas').getContext('2d'), o = 20; o; ) {
if (((i.font = o.toString(10) + 'px sans-serif'), i.measureText('W').width === t && i.measureText('m').width === e)) return o + 1;
((t = i.measureText('W').width), (e = i.measureText('m').width), o--);
}
return 0;
}
})(),
$ = {};
e.isSupported = V;
e.minFontSize = Z;
e.stop = function () {
if ($) for (var t in $) window.clearImmediate($[t]);
};
t.WordCloud = e;
})(window);
const WordCloud = window.WordCloud;
export const { isSupported, minFontSize, stop } = WordCloud;
export default WordCloud;
完结