CanML– Creating simple Markup language using XML + T4 for drawing shapes in HTML5 Canvas in your ASP.NET/C# applications

By Anoop Madhusudanan

Vote on HN

In this post, we’ll explore how to create a simple Xml based markup language for defining shapes for HTML5 Canvas. We’ll achieve this by generating JavaScript code from the Xml definition, and this post is intended to be a pointer towards how you can leverage scaffolding and meta programming to simplify a lot of scenarios.  If you don’t have a lot of kids to look after, modify this to create your own version of full fledged CanML (take that name) and let me know

Coming back - We’ll be using my Elastic Object Nuget package and T4 templates for code generation as I explained in my last post [Using AmazedSaint.ElasticObject Nuget Package for code generation], so reading that post will help for sure. I also suggest you to read quickly this Basic Canvas tutorial in MDN

[+] Source code -  Download ASP.NET MVC zipped example From Skydrive and keep it handy

What we are going to achieve?

You’ll be able to declare your canvas shapes using XML, for example see how I’m declaring a Heart shape and a Triangle slice. In the heart shape, I’m using absolute co-ordinates, and I’m using variables for triangle slice so that you can draw it anywhere.

<?xml version="1.0" encoding="utf-8" ?>

<shapes>

  <!--Normal Heart Shape, Fixed Coords-->
  <shape name="shapeHeart" type="fill" params="fillColor">
    <fillStyle value="fillColor"/>
    <to params="75,40"/>
    <bcurve params="75,37,70,25,50,25"/>
    <bcurve params="20,25,20,62.5,20,62.5"/>
    <bcurve params="20,80,40,102,75,120"/>
    <bcurve params="110,102,130,80,130,62.5"/>
    <bcurve params="130,62.5,130,25,100,25"/>
    <bcurve params="85,25,75,37,75,40"/>
  </shape>

  <!--Triangle Slice with variables-->
  <shape name="shapeTriangleSlice" type="fill" params="fillColor,firstX,firstY,delta">
    <fillStyle value="fillColor"/>
    <to params="firstX,firstY"/>
    <line params="firstX,firstY+delta"/>
    <line params="firstX+delta,firstY"/>
  </shape>


  <!--Draw both-->
  <shape name="allShapes">
    <shape name="shapeHeart" params="'yellow'"/>
    <shape name="shapeTriangleSlice" params="'red',200,200,100"/>
    <shape name="shapeTriangleSlice" params="'red',200,200,-100"/>
  </shape>
  
</shapes>

And this will be rendered to an HTML5 Canvas as below. This trick is, we are generating the required JavaScript code from the above markup, using the technique I explained in my earlier post – Generating code from simple XML models

 

image

 

What about the Generated JavaScript?

If you are interested to see the JavaScript getting generated from the above Markup, see that below. If you examine the generated code closely along with the xml model we’ve above, you can see that we are following a couple of simple conventions to generate the code from the above markup.

  • Each <shape/> definition is wrapped as a method, with a canvas parameter (along with other parameters if param element is present)
  • The type attribute of the Shape
  • We are having some short cut notations (like to –> moveTo and bcurve-> bezierCurveTo)
  • If an element has a param attribute, it’ll be rendered as a method (example is moveTo)
  • If an element has a value attribute, it’ll be rendered as a property (example is
//Method generated 
var shapeHeart = function (canvas, fillColor) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
	ctx.beginPath();
	ctx.fillStyle=fillColor;
	ctx.moveTo(75,40);
	ctx.bezierCurveTo(75,37,70,25,50,25);
	ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
	ctx.bezierCurveTo(20,80,40,102,75,120);
	ctx.bezierCurveTo(110,102,130,80,130,62.5);
	ctx.bezierCurveTo(130,62.5,130,25,100,25);
	ctx.bezierCurveTo(85,25,75,37,75,40);
	ctx.fill();			
}
}
//Method generated 
var shapeTriangleSlice = function (canvas, fillColor,firstX,firstY,delta) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
	ctx.beginPath();
	ctx.fillStyle=fillColor;
	ctx.moveTo(firstX,firstY);
	ctx.lineTo(firstX,firstY+delta);
	ctx.lineTo(firstX+delta,firstY);
	ctx.fill();
			
}
}
//Method generated 
var allShapes = function (canvas) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
	ctx.beginPath();
	shapeHeart(canvas,'yellow');
	shapeTriangleSlice(canvas,'red',200,200,100);
	shapeTriangleSlice(canvas,'red',200,200,-100);			
}
}
Note that all methods are generated with a canvas input parameter. And now, you may call these methods by linking to the generated CanvasShapes.js script file in your html page – See my index.cshtml ASP.NET MVC razor view where I invoke the allShapes method.  Just get your actual canvas element, and pass it to draw, as shown below.
@{
    ViewBag.Title = "Home Page";
}

@section headerSection{
    <script src="@Url.Content("~/CanvasShapes/CanvasShapes.js")" type="text/javascript"></script>
     <style type="text/css">  
      canvas { border: 1px solid black; margin-left:auto; margin-right:auto;}  
    </style>  
}

<canvas id="myCanvas" width=800 height=480></canvas>

<script>
    var canvas = document.getElementById("myCanvas");
    allShapes(canvas);
</script>

Tell me about the Actual Generation of JS from XML?

The actual generation is super simple – In fact this was just intended to be an sample use case for using the Elastic Object Nuget package for code generation.

To try this out manually,

  • Create a new ASP.NET MVC Project in Visual Studio.
  • Install the AmazedSaint.ElasticObject package as explained in my previous post – This will also add an Xml file and a TT (Text template file) to your project
  • Rename the Xml file to CanvasModel.xml – and copy the above XML code to the same
  • Rename the TT file CanvasShapes.tt, and add  the below T4 code to the TT File

Here is the simple T4 code we are using for generating the JS Code. Oops, the actual conversion code is not even 25 lines, but this is enough to convey the idea, right? You can beef this up further, by adding some support for gradiants, transitions etc to make this full fledged. Keep the MDN Canvas documentation handy.

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ Assembly Name="System.Xml.dll" #>
<#@ Assembly Name="System.Xml.Linq.dll" #>
<#@ Assembly Name="System.Core.dll" #>
<#@ Assembly Name="Microsoft.CSharp.dll" #>
<#@ Assembly name="$(SolutionDir)packages\AmazedSaint.ElasticObject.1.2.0\lib\net40\AmazedSaint.Elastic.dll" #>
<#@ Import Namespace="System.Xml" #>
<#@ Import Namespace="System.Xml.Linq" #>
<#@ Import Namespace="AmazedSaint.Elastic" #>
<#@ Import Namespace="System.Collections.Generic" #>
<#@ Import Namespace="System.Collections" #>
<#@ Import Namespace="AmazedSaint.Elastic.Lib" #>
<#@ output extension=".js" #>

<#
var model=FromFile("CanvasModel.xml");
foreach(var c in model["shape"])  //get all classes
	WriteShapeMethod(c);

#>

<#+ 
//Create an elastic object
private dynamic FromFile(string file)
{
   var path= Host.ResolvePath(file);
   return XDocument.Load(path).Root.ToElastic();
}

//Write a shape method
private void WriteShapeMethod(dynamic c)
{ 
#>
//Method generated 
var <#= c.name #> = function (<#=c.HasAttribute("params")
                         ?"canvas, " + c.@params :"canvas"  #>) 
{
if (canvas.getContext){  
    var ctx = canvas.getContext('2d');  
	ctx.beginPath();
<#+	
var tokens = new System.Collections.Generic.Dictionary<string, string>()
			{
				{"bcurve","bezierCurveTo"},
                {"qcurve","quadraticCurveTo"},
                {"line","lineTo"},
                {"to","moveTo"},
                {"arcTo","arcTo"}
			};
	foreach (var member in c[null])
    {
	    string mname = tokens.ContainsKey(member.InternalName) 
               ? tokens[member.InternalName] : member.InternalName;
        if (member.HasAttribute("params"))
        {
           if (member.InternalName=="shape")
		WriteLine("\t" + member.name + "(canvas," + member.@params + ");");
           else
	       WriteLine("\tctx." + mname + "(" + member.@params + ");");
   }
        else if (member.HasAttribute("value"))
	        WriteLine("\tctx." + mname + "=" + member.@value + ";");
        else
	        WriteLine("\tctx." + mname + "();"); 
	}

    if (c.HasAttribute("type"))
	    WriteLine("\tctx." + c.type + "();");
        
#>			
}
}
<#+
}

#>

All right, Happy coding as usual. Enjoy some simple meta coding cookies.

© 2012. All Rights Reserved. Amazedsaint.com