Use D3-cloud to present the label cloud in the Hexo static blog

Source: Internet
Author: User
Tags return tag

Effect: http://lucyhao.com/tags/

Hexo's Tag cloud labels are not very beautiful, and want to be able to show the "cloud" effect of the label. Found the D3-cloud on the Internet, GitHub address:https://github.com/jasondavies/d3-cloud Demo address:https:// www.jasondavies.com/wordcloud/

Hexo generated a static blog, so the last to see on the Internet is static content, that is, we see the tag cloud is also static generated content, does not refresh the page and recalculate the generation of another style of the label Cloud.

Of course D3-cloud This project, provides the browser side and the node side run version, see its example, we can run on the client side, can also be run as node on the server.

How to use it in the blog system built by Hexo?

(1) The method of tag cloud.js provided in Hexo, in your blog project, Node_modules-Hexo->plugins, helper, tagcloud.js

(2) This blog uses the Icarus theme, under the theme of the Layout->tags.ejs file load directory tags under the content

The tag cloud is loaded here, and Tagcloud is the function provided by the Tagcloud.js (1)  <div class= "Layout-wrap-inner tag-cloud" >    <% if ( Site.tags.length) {%>        <%-tagcloud ()%>    <%}%>  </div>

  

As you know, to modify the Hexo in the Tagcloud, just modify the tag cloud.js function can be ~

Now let's take a look at D3-cloud this project, how to combine it with Tagcloud. First, D3-cloud provides a way to run in the browser and on the server, see his example, node. js and Browserify.js. The reason for two different versions is that the Mesuretext interface of the canvas is used when calculating the width of the string. In D3-cloud's index.js source code, you can see that there is a line

function Cloudcanvas () {  return document.createelement ("canvas");//Generate Virtual Canvas}

  

Because in the calculation of the label cloud, to ensure that the label does not overlap, you need to know the width of the label, height, and the JS language does not have the ability to calculate, or the use of a browser, to generate a DOM, such as a span tag, the contents of the string into a span, Set the properties of the span to the properties that the string needs to display, and then get the width of the span. In D3-cloud, it is implemented directly using the interface of the canvas. So in the client version, the browser provides the canvas functionality, whereas in the node version, the Node-canvas module is required.

Since we are in the Hexo "backstage" to run the tag cloud algorithm, get the statically constructed label output to the page, so we should choose the node version. Of course, you can also use the Browserify.js version, after all, he is a running in the browser JS, put in the blog JS is also possible, follow-up will be introduced.

take advantage of the problems encountered by Node-canvas

Node-canvas module Mesuretext for Chinese support has a bug, in Chrome, the same Chinese string "Hello" width is 33.*, and the Node-canvas to the "Hello" width only 8.*

What to do? I am opportunistic, with two English characters "AB" instead of a Chinese character, and then calculate the length of the string, so that the length is approximate length.

formally began to modify the Hexo to D3-cloud's label Cloud

(1) Install the required modules:

$ npm Install canvas--save$ npm install d3-cloud--save$ npm install D3--save (optional)

  

(2) Find file: Your blog item, node_modules, Hexo->plugins, helper, index.js

  var Tagcloud = require ('./tagcloud ');  Helper.register (' Tagcloud ', tagcloud);  Helper.register (' Tag_cloud ', Tagcloud);?  Modify the code to the following: The intent is not to modify tagcloud.js directly, preserving the code  var tagcloud = require ('./tagcloud ');  var tagcloudd3 = require ('./tagcloudd3 ');  Helper.register (' Tagcloud ', tagcloudd3);  Helper.register (' Tag_cloud ', tagcloudd3);

  

(3) New file Tagcloudd3.js: Location in Blog project, Node_modules, Hexo->plugins, helper, tagcloudd3.js

(4) The contents of Tagcloudd3.js are as follows:

    • The code refers to the D3 to give the label fill color, can be removed, or can be like tagcloud depending on whether the need for color to set

' Use strict ';? var canvas = require ("Canvas"), var cloud = require ("D3-cloud"), var d3 = require ("D3");?    var layout = Cloud ()//Use D3-cloud to calculate the position of each label. Size ([+]). Canvas (function () {return new canvas (1, 1);})    . padding (7). Rotate (function () {return ~ ~ (Math.random () * 2) * 90;}) . Font ("Impact"). FontSize (function (d) {return d.size;}); var fill = d3.scale.category20 ();//Use D3 interface to give each label color? function Tagcloudhelper (tags) {/**** and tagcloud.js, get tags start ***/if ((!tags | |!tags.hasownproperty (' length ')))  {tags = this.site.tags;  }?    if (!tags | |!tags.length) return ';  var result = [];?  tags = tags.sort (' name ', 1);?  Ignore tags with zero posts tags = tags.filter (function (tag) {return tag.length; });  /**** and tagcloud.js like, get tags end ***///Calculate the maximum number of label occurrences, for example, the blog has a total of two tags, one is Hello, one is World,hello 2 times, World appears 1 times, then MaxSize is 2  var maxsize = 1;?    Tags.sort (' length '). ForEach (function (tag) {var length = Tag.length;  if (length > maxsize) maxsize = length; });?  Build the words var arr = [],words] of the incoming layout;  Tags.foreach (function (tag) {Arr.push ({"Name": Tag.name, "num": Tag.length});  }); Words = Arr.map (function (d) {var text = D.name.replace (/[^\x00-\xff]/g, "AB");//speculative handling of Chinese, use AB instead Chinese character return {name: D.name, Text:text, Size:Math.log (d.num)/(Math.log (MaxSize)-math.log (1)) * The computed logarithm of the + 30};//size is to make the size of the labels relatively average.      Because the blog focus on the front-end content, so some of the labels will be more, the maximum minimum number of labels the gap will be relatively large.  });  Layout.words (words);  Layout.start ();?  Result.push (' <svg width= ' "height=" ><g transform= "translate (300,200)" > ");    Words.foreach (function (word,i) {? Result.push (' <text text-anchor= ' middle "fill=" ' +fill (i) + ' "transform=" translate (' +word.x+ ', ' +word.y+ ') rotate ('     + word.rotate+ ') "style=" font-size: ' +word.size+ ' px;font-family:impact ' > ' + word.name+ ' </text> '  );  });    Result.push (' </g></svg> ');  Return Result.join ("); }module.exports = Tagcloudhelper;

  

(5) Running Hexo

$ hexo S

  

Get your own tag cloud:

(6) Upload your own blog, no problem later, build a static blog, and upload

$ hexo g$ Hexo D

Simply say in the client reference D3-cloud

(1) browserify compiled D3-cloud provided browserify.js example, get Tagtest.js file, inside the D3,d3-cloud,d3-dispatch packed together

$ browserify broswerify.js > Tagtest.js

(2) Put Index.js in the catalogue: your theme->source-js---Tagtest.js

(3) index reference into your subject <%-JS (' js/tagtest ')%>

(4) Modify the code in the Tagtest.js, the words part of the change to accept the form of parameters, in the Tags.ejs with the site.tags the parameters of tags in

This will add a lot of JS in the blog, the personal feel a bit against the static blog small and light feeling ...

Use D3-cloud to present the label cloud in the Hexo static blog

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.