Rotate a Shape Around an Axis Using HTML5 and Javascript

Imagine, for a minute, that you want to rotate a red square around its centre… on a web page. Following on from my previous post about games using HTML5 / JS this post details how to do such a thing.

Context

Before drawing a rectangle, rotating it, or anything else, you need a context:

var canvas = document.getElementById("mainCanvas");
var ctx = canvas.getContext("2d");

Now you have a context, you can do things like clear the canvas; for example:

ctx.clearRect(0, 0, windowWidth, windowHeight);

fillRect

In HTML5, you have three methods that will be of use, and the first, and probably most important, is fillRect. It is impossible to rotate a square around its centre without a square. The syntax for fillRect is probably as you would expect:

ctx.fillRect(x, y, width, height);

rotate

The syntax for rotation is this:

ctx.rotate(rotationDegree * Math.PI / 180);

Whilst I may, during my school years, have been able to explain the sum above – I just copied it from the internet. Given the number of places where is looks exactly alike, I would guess that I’m not the first person to do that.

Just using the three lines above will give you a rotating rectangle; however, the rotation axis will be 0, 0. It took me a while to understand exactly how this works, but the key is `translate`.

translate

To me, this function is completely counter-intuitive. What it does it to offset the centre of the context by the parameters given. If the initial centre is 0, 0 (which it is by default), the following line will make it 10, 10:

ctx.translate(10, 10);

The centre of the context is 10, 10; if I call it a second time:

ctx.translate(10, 10);

The centre of the context is now 20, 20! There are two ways to reset the offset – you can simply negate the offset (by calling it with negative values), or you can call ctx.save() before the change, and ctx.restore() afterwards.

Putting it all together

So, what does all this look like in a single coherent piece of code:


        var canvas = document.getElementById("mainCanvas");
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, windowWidth, windowHeight);

        var halfWidth = (iconWidth / 2);
        var halfHeight = (iconHeight / 2);

        var centreX = x - halfWidth;
        var centreY = y - halfHeight;

        ctx.fillStyle = "#FF0000";
        ctx.translate(centreX, centreY);
        ctx.rotate(rotationDegree * Math.PI / 180);
        ctx.fillRect(-halfWidth, -halfHeight, iconWidth, iconHeight);

        ctx.translate(-centreX, -centreY);

The key part to note here is the call to fillRect. Because the translate has now set the centre to be the centre of the drawn image, the image needs to be positioned at -(image width / 2).

… and you, too can have a spinning red rectangle on your screen.

References

http://www.w3resource.com/html5-canvas/html5-canvas-translation-rotation-scaling.php

https://gist.github.com/geoffb/6392450

Basic Game Using HTML5 and Javascript

This article discusses how to go about creating a basic game loop in HTML5 / JS and to implement control over a sprite.

Introduction

A few years ago, when Microsoft released the idea of WinJS, I wrote a game in HTML5/JS (or WinJS – they are not exactly the same).

I recently decided to see if I could write a web game, using just HTML5 and Javascript. This article covers the initial POC and results in a small red square navigating around the screen:

Game Loop

Looking at established game frameworks, they all basically give you the same things:
– A game loop, consisting of an update and draw phase
– Some helper methods for manipulating graphics, or rendering them to the screen

My attempt will be different, I’ll just provide a game loop; here it is:

(function MainGame() {    

    setInterval(function() {
        Update();
        Draw();
    }, 20);
})();

The loop executes every 20ms, meaning that there are 50 frames per second.

HTML

Basically, what the HTML gives us here is a canvas; so the page is very simple:

<head>    
    <script type="text/javascript" src="./gamelogic.js" ></script>
</head>
<body onresize="onResizeGameWindow()">    
    <canvas id="mainCanvas" style="width: 100%; height: 100%"
        onkeydown="onKeyDown()" tabindex="0">
    </canvas>
</body>

There are two events handled here, because there are two things that the player can do: they can interact with the game (i.e. press a key), and they can resize the browser window. We need to react to both.

Draw

Let’s have a look at the draw function next. All this is, is a way of displaying all the objects on the screen in a controlled fashion:


    function Draw() {
        var canvas = document.getElementById("mainCanvas");
        var ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, windowWidth, windowHeight);

        ctx.fillStyle = "#FF0000";
        ctx.fillRect(x, y, iconWidth, iconHeight);
    }

As you can see, there are effectively two parts to this function: firstly, the canvas is cleared, and then the items (in this case, a single item) are drawn to the screen. The important variables here are x and y, because that dictates where the square is drawn; the rest could be hard-coded values.

Update


    function Update() {        
        if (initialised == 0) {
            initialise();
        }

        // Bounce
        if (x >= (windowWidth - iconWidth) 
            && directionX > 0)
            directionX = -1;
        else if (x <= 0 && directionX < 0)
            directionX = 1;

        if (y >= (windowHeight - iconHeight)
            && directionY > 0)
            directionY = -1;
        else if (y <= 0 && directionY < 0)
            directionY = 1;

        // Move
        x += directionX * speed;
        y += directionY * speed;
    }

There are three parts to the Update. The first is to perform any initialisation: in my case, I focus on the canvas and call the resize event here. This potentially could be done on an event, but you would still have to check inside this loop if it had been done. The second is to stop the player leaving the screen; and finally, we adjust the player position.

Events

As you saw earlier, there are two events that are handled; the first is the user resizing the screen:

function onResizeGameWindow() {
    var canvas = document.getElementById("mainCanvas");
    
    windowWidth = canvas.width;
    windowHeight = canvas.height;
}

This basically ensures that the game adjusts to the browser dimensions. This might also be where you would determine if the window was made so small that the game could no longer be played.

The second event was the keydown event. This effectively provides the control for the player:


function onKeyDown(e) {
    if (!e) e = window.event;     

    if (e.keyCode == 39) {
        directionX++;
    }
    else if (e.keyCode == 37) {
        directionX--;
    }

    if (e.keyCode == 38) {        
        directionY--;
    }
    else if (e.keyCode == 40) {        
        directionY++;
    }
}

The top line is because the parameter comes through as null.

Conclusion

If you run this game, you’ll see that you can move the square around the screen, increase and decrease its speed, and stop. Not exactly the next Call Of Duty, I’ll grant you, but the foundation of a game, certainly.

Live Testing in Visual Studio 2017

While working on this project, I decided that I would see how useful the new feature of “Live Testing” is for TDD.

Once you’ve created your suite of tests, turning live testing on gives you some interesting information:

As you can see, there are some slight contradictions here in what it’s telling me. The first test is failing, the test for Count has a line (which indicates not covered). However, code lens is telling me there are two covering tests.

My suspicion here is that live testing is being too clever for its own good; for example, looking at the tests themselves, shows that only the first Enqueue statement is covered:

My thoughts are that the engine works out where the test fails, and so, in the case above, it’s telling me that the tests are not running the line of code that tests the Count functionality. What I’m guessing is that this is because the tests are failing before that.

I can prove this by creating a further unit test:

And, indeed, this now shows coverage:

As I start to add the functionality, I can quickly see that the tests are now passing:

Changing the way code is written

The interesting thing here is that is promotes two things:
1. Defined tests – if a test covers more than one thing, it will show as uncovered initially
2. Tests first – obviously, there need to be tests to show test coverage

Caveats

1. Annoyingly, by default, you continually have to opt in for live unit testing. It only starts when you select to “Start” live unit testing, and this must be done each time you launch VS. This is configurable, and can be switched on by default in options:

2. If the build fails, it shows nothing.

3. Live testing is only available in Visual Studio Enterprise.

NUnit

One thing that only occurred to me as notable while I was writing this is that the tests that I’ve written are in NUnit. So the Live Testing clearly works with none MSTests, and probably works with anything that’ll show up in Test Explorer / Code Lens.

References

https://blogs.msdn.microsoft.com/visualstudio/2017/03/09/live-unit-testing-in-visual-studio-2017-enterprise/

Bing Maps – Finding an Address from Longitude / Latitude

Oddly, finding an address from given coordinates is not as straightforward as it first appears. The key seems to be to use the SearchManager.

SearchManager

The following is a typescript implementation that will populate an input element called myLocationText:


function GetMap(position): void {    
    map = new Microsoft.Maps.Map(
        document.getElementById('map'),
        { credentials: "MyKey" });

    Microsoft.Maps.loadModule('Microsoft.Maps.Search', function () {
        var searchManager = new Microsoft.Maps.Search.SearchManager(map);
        var location = new Microsoft.Maps.Location(position.latitude, position.longitude);
    
        var mapOptions = {        
            center: location,        
            mapTypeId: Microsoft.Maps.MapTypeId.aerial,
            zoom: 10,        
            showScalebar: false        
        }    

        var reverseGeocodeRequestOptions = {
            location: location,
            callback: function (answer, userData) {
                map.setView(mapOptions);
                var myLocation = <HTMLInputElement>document.getElementById('myLocationText');                
                myLocation.value = answer.address.formattedAddress;
            }
        }
        searchManager.reverseGeocode(reverseGeocodeRequestOptions);
    });

If you want to get it to show your current location, then try this:


function findMe(position) : void {
   
    var latlong = new Microsoft.Maps.Location(position.coords.latitude,
        position.coords.longitude);

    GetMap(latlong);
    
}

Shows the correct address

References

http://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk#searchByPoint+JS

http://bingmapsv8samples.azurewebsites.net/#Calculate%20Distance%20From%20Route

https://www.nuget.org/packages/Microsoft.BingMaps.V8.TypeScript/

TypeScript

Javascript is a dynamic, interpreted language. What that means is that, if you mis-type or mis-spell a variable, or even if you don’t bother to declare it, you won’t get notified at compile time (because, for a start, there is no compile time).

One possible way around this is to use one of the languages that compile down to Javascript. That does seem like a bizarre notion – that you should compile down to a second language; but it does mean (as the name suggests) that you can introduce some static typing into your Javascript.

The following was with VS2017, but you can use VS2015. I believe earlier versions don’t support Typescript out of the box (but I could be wrong).

Javascript

The first thing we’ll do is create a new web project and create some Javascript:

Create new project

Create new project

Create a basic html page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    
</head>
<body>
    <div>
        <input id="testInput" type="text" />
    </div>
    <div>
        <p id="testOutput">Output</p> 
    </div>
    <div>
        <button onclick="buttonClicked()">Test</button>
    </div>

    <script src="typescript.js"></script>

    
</body>

And the Javascript:

function buttonClicked() {
    var input = getElementById("testInput");
    var ouput = getElementById("testOutput");

    output.value = input.value;

}

This code will run (the web-site will appear), but it will not do what it’s supposed to.

Typescript

Now we have a project, the next thing to do is to add .ts file to project. This gets compiled into a .js file, and can be referenced with a .js extension. Just copy the code:

Code sample

As you can see, the code no-longer “compiles”. The correct Typescript looks more like this:

function buttonClicked() {
    var input = <HTMLInputElement>document.getElementById("testInput");
    var output = document.getElementById("testOutput");

    output.innerText = input.value;

}

The <> brackets are typescript casts. Once you build this typescript file, it will compile down to Javascript:

Project tree

The compiled Javascript now looks like this:

function buttonClicked() {
    var input = document.getElementById("testInput");
    var output = document.getElementById("testOutput");
    output.innerText = input.value;
}
//# sourceMappingURL=typescript.js.map

The typescript.js.map file tells it where your file really is and, from looking at the debugger, we can see that the typescript file is being used:

All works well:

But why

As you can see, above; we had a piece of Javascript code that didn’t work, but it ran. Any statically typed language would have simply failed to compile. Typescript means that you can benefit from this additional check before runtime. There is a cost here, and that is that you lose the dynamic typed capability of Javascript; for example, the following won’t compile:

IMHO, this is a good thing, but I’m aware there are people out there in the world that think otherwise.

References

http://stackoverflow.com/questions/34888434/how-to-reference-a-typescript-file-from-a-web-page

http://stackoverflow.com/questions/12686927/typescript-casting-htmlelement

NUnit TestCaseSource

While working on this project, I found a need to abstract away a base type that the unit tests use (in this instance, it was a queue type). I was only testing a single type (PriorityQueue); however, I wanted to create a new type, but all the basic tests for the new type are the same as the existing ones. This led me to investigate the TestCaseSource attribute in NUnit.

As a result, I needed a way to re-use the tests. There are definitely multiple ways to do this; the simplest one is probably to create a factory class, and pass in a string parameter. The only thing that put me off this is that you end up with the following test case:

        [TestCase("test", "test9", "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9"]
        [TestCase("a1", "a", "a1", "b", "c", "d", "a"]
        public void Queue_Dequeue_CheckResultOrdering(
            string first, string last, params string[] queueItems)
        {

Becoming:

        [TestCase("PriorityQueue", "test", "test9", "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9"]
        [TestCase("PriorityQueue2", "test", "test9", "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9"]
        [TestCase("PriorityQueue", "a1", "a", "a1", "b", "c", "d", "a"]
        [TestCase("PriorityQueue2", "a1", "a", "a1", "b", "c", "d", "a"]
        public void Queue_Dequeue_CheckResultOrdering(
            string queueType, string first, string last, params string[] queueItems)
        {

This isn’t very scaleable when adding a third or fourth type.

TestCaseSource

It turns out that the (or an least an) answer to this is to use NUnit’s TestCaseSource attribute. The NUnit code base dog foods quite extensively, so that is not a bad place to look for examples of how this works; however, what I couldn’t find was a way to mix and match. To better illustrate the point; here’s the first test that I changed to use TestCaseSource:

        [Test]
        public void Queue_NoEntries_CheckCount()
        {
            // Arrange
            PQueue.PriorityQueue<string> queue = new PQueue.PriorityQueue<string>();

            // Act
            int count = queue.Count();

            // Assert
            Assert.AreEqual(0, count);
        }

Which became:

        [Test, TestCaseSource(typeof(TestableQueueItemFactory), "ReturnQueueTypes")]
        public void Queue_NoEntries_CheckCount(IQueue<string> queue)
        {
            // Arrange


            // Act
            int count = queue.Count();

            // Assert
            Assert.AreEqual(0, count);
        }

(For completeness, the TestableQueueItemFactory is here):

    public static class TestableQueueItemFactory
    {
        public static IEnumerable<IQueue<string>> ReturnQueueTypes()
        {
            yield return new PQueue.PriorityQueue<string>();
        }
    }

However, when you have a TestCase like the one above, there’s a need for the equivalent of this (which doesn’t work):

        [Test, TestCaseSource(typeof(TestableQueueItemFactory), "ReturnQueueTypes")]
        [TestCase("test", "test9", "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9")]
        [TestCase("a1", "a", "a1", "b", "c", "d", "a")]
        public void Queue_Dequeue_CheckResultOrdering(string first, string last, params string[] queueItems)
        {

A quick look at the NUnit code base reveals these attributes to be mutually exclusive.

Compromise

By no means is this a perfect solution, but the one that I settled on was to create a second TestCaseSource helper method, which looks like this (along with the test):

        private static IEnumerable Queue_Dequeue_CheckResultOrdering_TestCase()
        {
            foreach(var queueType in TestableQueueItemFactory.ReturnQueueTypes())
            {
                yield return new object[] { queueType, "test", "test9", new string[] { "test", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9" } };
                yield return new object[] { queueType, "a1", "a", new string[] { "a1", "b", "c", "d", "a" } };
            }
        }

        [Test, TestCaseSource("Queue_Dequeue_CheckResultOrdering_TestCase")]
        public void Queue_Dequeue_CheckResultOrdering(
            IQueue <string> queue, string first, string last, params string[] queueItems)
        {

As you can see, the second helper method doesn’t really help readability, so it’s certainly not a perfect solution; in fact, with a single queue type, this makes the code more complex and less readable. However, When a second and third queue type are introduced, the test suddenly becomes resilient.

YAGNI

At first glance, this may appear to be an example of YAGNI. However, in this article, Martin Fowler does state:

Yagni only applies to capabilities built into the software to support a presumptive feature, it does not apply to effort to make the software easier to modify.

Which, I believe, is what we are doing here.

References

http://www.smaclellan.com/posts/parameterized-tests-made-simple/

http://stackoverflow.com/questions/16346903/how-to-use-multiple-testcasesource-attributes-for-an-n-unit-test

https://github.com/nunit/docs/wiki/TestCaseSource-Attribute

http://dotnetgeek.tumblr.com/post/2851360238/exploiting-nunit-attributes-valuesourceattribute

https://github.com/nunit/docs/wiki/TestCaseSource-Attribute

Create a Web Page to Find an Address Using Bing Maps 6.3

This post discusses how you might implement an address search with Bing Maps.

Disclaimer

I know that Bing Maps 6.3 is shortly to be deprecated. When I get around to signing up for v8 I might post an update to this.

Display the map

Below is a basic HTML page that has a map control. For details on how that works, please see here.

    <form class="row">
        </div>                

        <div class="overlay">
            <input type="text" id="destination" placeholder="Where do you want to go?" 
                   class="input-overlay" oninput="ChangeDestination(this.value);" />
        </div>        
    </form>

    <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script>
    <script type="text/javascript" src="~/Scripts/MyScript.js"></script>

There’s not too much to note in this HTML, with the possible exception of the oninput function. I spent a while trying to get onchange and onkeypress to work, but oninput is a HMTL5 specific feature, and it fires when there is a change in the input box; onchange does not. onkeypress does, but you’re always a key-stroke behind.

Here’s the Javascript function in MyScript.js (referenced above):

function ChangeDestination(text) {
    map.Find("", text);
}

This causes Bing Maps to go looking for the address that you pass it. It still needs work, as you will see if you start typing any place name – it’ll match whatever you’ve typed as best it can… and you’ll travel the world before you get where you’re going.

Further Thought

One possible work around for this might be to poll the text from javascript every second and determine whether it changed; however, there is another approach:

First, change the HTML to point to a caller function:

            <input type="text" id="destination" placeholder="Where do you want to go?" 
                   class="input-overlay" oninput="callChangeDestination(this.value);" />

And then, set a timeout, so that the function is only called if we don’t re-call it within a second:

var timeout;
function callChangeDestination(text) {
    
    clearTimeout(timeout);
    timeout = setTimeout(function () { ChangeDestination(text); }, 1000);       
}

Change the ChangeDestination function itself to clear the timeout:


function ChangeDestination(text) {
    clearTimeout(timeout);
    …

Now, as you type, it will only update the map when you pause.

References

http://stackoverflow.com/questions/20420429/what-the-difference-between-window-settimeout-and-settimeout

Convert a standard C# project into a Unit Test project

I recently (accidentally) created a Unit Test project as a standard C# class library. Although you don’t need to change this to a test library (it basically just gives you the test icon instead of the class icon), I felt that, if I wanted to do this, it shouldn’t require that I delete and recreate the project.

To change the project type

If you open the csproj for a class library, it looks like this (or some of it does):

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{93F28F24-AD9B-4839-8697-6DA48BAB2048}</ProjectGuid>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>MyProject.UnitTests</RootNamespace>
    <AssemblyName>MyProject.UnitTests</AssemblyName>
    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>

All you need to do is add the correct ProjectTypeGuids:

<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

References

https://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs

http://stackoverflow.com/questions/2911565/what-is-the-significance-of-projecttypeguids-tag-in-the-visual-studio-project-fi

CSS Overlaying Controls (absolute and relative positioning)

Having looked at CSS in the past, and thought that it’s probably something that people who are better at UI design that me should concern themselves with, I’ve recently been playing with it while looking at the new Dot Net Core web apps.

The problem that I’m looking at in this particular article is how to overlay one control on top of another. I have no doubt that there are dozens of possibilities; but the two specific ones that I’ll be focusing on are positioning absolute and relative.

Target

The idea here is for a web-page that looks like this:

Target Layout

HTML

The HTML is pretty basic for this:

<body>
  <form>
    <div>
      <img src=""  />
    </div>
    <div class="overlay">
      <input type="text" name="destination" />
    </div>
  </form>
</body>

CSS: absolute positioning

We have the basic elements, so now it’s down to CSS to make the screen above. By default, web browsers will render the div’s sequentially, and so the input box will appear below the image.

One possibility is to use “absolute” positioning. This means that I can position an element without regard to where other elements on the page might be; here’s an example:

.overlay {
    position: absolute; 
    top: 30%;         
    text-align: center;
    z-index: 10;
}

img {
  background-color: blue;
  width: 100%;
  height: 500px;
}

I’ve used 30% here because it matters on the size of your viewport – so that’s not ideal. Also, the centre align doesn’t work. This kind of makes sense when you think about it, because you’re using an absolute position – so what do you want to centralise it to?

CSS: relative positioning

Relative positioning took me a while to work out. It sounds like it’s relative to something else – but it’s actually relative to itself. Here’s what I tried for relative positioning:

.overlay {
    position: relative;
    width: 80%;
    height: 35px;
    top: -50px;
    border: none;
    text-align: center;
    z-index: 10;    
}

As you can see, it’s top position is negative, so it moves up from where it would have been. Also, because the positioning is relative, the centre align now works, because it’s back in the flow of the page.

References

https://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

https://www.w3.org/Style/Examples/007/center.en.html#block

Find user’s current location and display on Bing maps (v6.3)

Using Bing Maps to display the user’s current position should be an easy task. As with everything in Javascript, this kind of thing is only easy if you know the magic text.

HTML

<body onload="LoadMap();">
    <div class="row">
        <div>
            <h2>Where do you want to go?</h2>
        </div>
    </div>

    <div class="row">        
        <div id="pnlMap" style="position:relative">
        </div>
    </div>

There are a few points here: first one is that you need a name for the pnlMap (referenced later is the javascript), and style=”position:relative” prevents the map from just displaying in a random location.

Javascript

var map;

function LoadMap() {        
    map = new VEMap('pnlMap');    
    navigator.geolocation.getCurrentPosition(findMe);
}

function findMe(position) {
          
    var latlong = new VELatLong(position.coords.latitude,
        position.coords.longitude);
    map.LoadMap(latlong, 10);
}

LoadMap() sets up the map variable and associates it to the relevant HTML control, and then getCurrentPosition calls back to findMe(). The second number on LoadMap is the zoom level; 1 shows me as living on the earth, and 20 goes right into the road that I live on.

The output is a map that centres on your current location:

Slightly offset to avoid hordes of angry JS programmers beating down my door and suggesting that dynamically typed languages are as good as statically typed ones!

V6.3

As you will see from the references below, the latest version is v8. If you use v8, then you have to register for a key… but I didn’t want to… and I still got a map. I suppose I’ve done a bad thing.

References

https://www.w3schools.com/html/html5_geolocation.asp

https://msdn.microsoft.com/en-us/library/bb259692.aspx

https://msdn.microsoft.com/en-us/library/cc161074.aspx

https://social.technet.microsoft.com/wiki/contents/articles/34568.bing-maps-v6-3-to-v8-migration-guide.aspx

http://stackoverflow.com/questions/42607156/using-bing-maps-with-bootstrap