Skip to main content

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

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.

Popular posts from this blog

Top 7 Coding Standards & Guideline Documents For C#/.NET Developers

Some time back, I collated a list of 7 Must Read, Free EBooks for .NET Developers, and a lot of people found it useful. So, I thought about putting together a list of Coding Standard guidelines/checklists for .NET /C# developers as well.As you may already know, it is easy to come up with a document - the key is in implementing these standards in your organization, through methods like internal trainings, Peer Reviews, Check in policies, Automated code review tools etc. You can have a look at FxCop and/or StyleCop for automating the review process to some extent, and can customize the rules based on your requirements.Anyway, here is a list of some good Coding Standard Documents. They are useful not just from a review perspective - going through these documents can definitely help you and me to iron out few hidden glitches we might have in the programming portion of our brain. So, here we go, the listing is not in any specific order.1 – IDesign C# Coding StandardsIDesign C# coding stand…

Creating a quick Todo listing app on Windows using IIS7, Node.js and Mongodb

As I mentioned in my last post, more and more organizations are leaning towards Web Oriented Architecture (WOA) which are highly scalable. If you were exploring cool, scalable options to build highly performing web applications, you know what Node.js is for.After following the recent post from Scott Hanselman, I was up and running quickly with Node.js. In this post, I’ll explain step by step how I’ve setup Node.js and Mongodb to create a simple Todo listing application.Setting up Node.jsThis is what I’ve done.1 – Goto http://nodejs.org/, scroll down and download node.exe for Windows, and place it in your c:\node folder2 – Goto IIS Node project in Git at https://github.com/tjanczuk/iisnode, download the correct ‘retail’ link of IIS Node zip file (I downloaded the already built retail package, otherwise you can download and build from the source).3 – Extract the zip file some where, and run the install.bat or install_iisexpress.bat depending on your IIS Version. If you don’t have IIS in…

5 Awesome Learning Resources For Programmers (To help you and your kids to grow the geek neurons)

Happy New Year, this is my first post in 2012. I’ll be sharing few awesome learning resources I’ve bookmarked, and will be pointing out some specific computer/programming related courses I've found interesting from these resources.Also, thought about saving this blog post for my kids as well - instead of investing in these Child education schemes (though they are too small as of today, 2 years and 60 days respectively ). Anyway, personally my new year resolution is to see as much videos from this course collections (assuming I can find some free time in between my regular job && changing my babies diapers).1 – Khan AcademyAs I mentioned some time back, you and your kids are missing some thing huge if you havn’t heard about Khan Academy.  It is an awesome learning resource, especially if you want to re-visit your basics in Math, Science etc.With a library of over 2,600 videos covering everything from arithmetic to physics, finance, and history and 268 practice exercises, th…