While d3-cloud itself is compatible with both D3 V3 and V4, most examples you will find are not, and your current code is not, it can only work with V3.

To make it work with V4 you need to replace all references to d3.scale. For example, d3.scale.category20() becomes d3.scaleOrdinal(d3.schemeCategory20). For a small runnable example that is compatible with both, see Fiddle #1. It uses RequireJS to load d3, d3-cloud, and jQuery. Try changing the D3 version in require config at top of JS part.

Let's settle on V3 for now, since your code relies on it. There are still a few issues:

Your must use objects for d3 & d3cloud & jQuery that are obtained via a call to require. And with RequireJS this is asynchronous (because it needs to fetch the JS scripts programmatically, and in a browser that can only be done asynchronously). You put your code within a callback function (for more info, see RequireJS docs):

[ Edit: see Jason's answer for alternative syntax. ]

require(['d3', 'd3cloud', 'jQuery'], function(d3, d3cloud, $) {
    /* Your code here.
       Inside "require" function that you just called,
       RequireJS will fetch the 3 named dependencies,
       and at the end will invoke this callback function,
       passing the 3 dependencies as arguments in required order.

In this context (and versions) d3 cloud main function is not available under, so you need to replace that with d3cloud(), assuming that's the name of the argument passed as callback to require.

You must make sure you never pass width or height of 0 to d3cloud.size([width, height]), or it will enter an infinite loop. Unfortunately it can easily happen if you use $(selector).height(), depending on content of your page, and possible "accidents". I suggest var height = $(selector).height() || 10; for example.

Not a programming problem, but the function you pass to .rotate() is taken from an example, and maybe you want to change that: it yields only 2 possible values, 0 or 90, I find this monotonous, the default one is prettier. So I removed the line entirely in the example below. Maybe you'll want it back, just add your .rotate(...) line.

Fiddle #2: a complete working example based on your piece of code.


The latest version of d3-cloud only depends on d3-dispatch so it should work fine with any version of D3. I think the issue here is that you're using RequireJS (AMD) to reference the file, but you're not using RequireJS to use the library (configured as cloud in your example). See the following example:

  baseUrl: ".",
  paths: {
    cloud: "" // refers to ./

requirejs(["cloud"], function(cloud) { // depends on "cloud" defined above
    .size([100, 100])
    .words([{text: "test"}])
    .on("word", function() {
      console.log("it worked!");

If you prefer to use CommonJS-style require(…) you can also use this with RequireJS if you use the appropriate define(…) syntax, like in this quick example.

Related Query