Basic usage

The most import method in the CdlUtils object for rendering CDL is:

CdlUtils.getSvgPathStrings(charOrUnicode, options);

This method returns a promise containing an array of SVG pathstrings. These pathstrings are designed to be used as the d attribute of an SVG path element. This method can be used as below:

CdlUtils.getSvgPathStrings('你', {
  width: 200, // px
  height: 200, // px
  apiKey: 'your-api-key'
}).then(function(pathStrings) {
  // do something exciting with the pathStrings
});

CdlUtils makes extensive use of Promises (the .then(... in the code above). If you're not already familiar with Promises, don't worry! Promises are discussed in more detail here.

Rendering Character SVG

CdlUtils returns SVG pathstrings from getSvgPathStrings which gives you complete freedom in terms of how to render the character. Below is an example of rendering the pathstrings as a static SVG image into the DOM:

CdlUtils.getSvgPathStrings('你', options).then(function(pathStrings) {
  var svg = document.getElementById('target');
  pathStrings.forEach(function(pathString) {
    var path = document.createElementNS("http://www.w3.org/2000/svg","path");
    path.setAttribute("d", pathString);
    path.setAttribute("fill", "#333"); // choose the color of the stroke
    svg.appendChild(path);
  });
});

And then in HTML we would expect an SVG tag like so:

<svg id="target"></svg>

For more advanced effects and animations it's best to use a library to manage SVG rendering. Below is an example of rendering a character using the svg.js SVG library, but you can use any SVG library you're comfortable with.

CdlUtils.getSvgPathStrings('你', options).then(function(pathStrings) {
  var svg = SVG('target');
  pathStrings.forEach(function(pathString) {
    svg.path(pathString).fill('#333');
  });
});

In this case the HTML would look like:

<div id="target"></div>

As you can see, managing SVG using a library is much cleaner!

Working with Promises

The CdlUtils library makes heavy use of Promises for async operations, and these docs assume you are comfortable using them. If you're not used to working with Promises in Javascript they can seem a bit confusing at first, but don't worry! It's really simple once you're used to it, and Promises are the direction the Javascript community is heading. If you're having trouble, check out http://www.html5rocks.com/en/tutorials/es6/promises/.


Note: Promises in Internet Explorer
Internet Explorer doesn't support Promises natively before Edge, so if you'd like to use CdlUtils with IE you'll need to polyfill the Promises API yourself. An easy way to do that in a webpage is to add the following script to your page before including cdl-utils.js:

<script type="text/javascript">
window.Promise || document.write('<script src="https://unpkg.com/es6-promise@4.0.5/dist/es6-promise.min.js"><\/script>');
</script>