A blog about one man's journey through code… and some pictures of the Peak District

Category Archives: Javascript

In this post I started looking into ReactJS. Following getting the sample project running, I decided that I’ve try adding a new screen. Since it didn’t go as smoothly as I expected, I’ve documented my adventures.

The target of this post is to create a new screen, using the sample project inside Visual Studio.

Step 1

Create a brand new project for React:

If you run this out of the box (if you can’t because of missing packages then see this article), you’ll get a screen that looks like this:

I’ve recently started looking into the Javascript library ReactJS. Having read a couple of tutorials and watched the start of a Pluralsight video, I did the usual and started creating a sample application. The ReactJS template in VS is definitely a good place to start; however, the first issue that I came across was with NPM.

Upon creating a new web application, I was faced with the following errors:

The reason being that, unlike NuGet, npm doesn’t seem to sort your dependencies out automatically. After playing around with it for a while, this is my advice to my future self on how to deal with such issues.

The best way for force npm to restore your packages seems to be to call

npm install

either from Powershell, or from the Package Manager Console inside VS.

Powershell

On running this, I found that, despite getting the error shown above, the packages were still restored; however, you can trash that file:

Following that, delete the node_modules directory and re-run, and there are no errors:

Package Manager Console

In Package Manager Console, ensure that you’re in the right directory (you’ll be in the solution directory by default, which is the wrong directory):

I was interested to see how playing multiple videos simultaneously affected the performance of a web page. This probably seems a little like a time machine back to 1995 – I’ll soon be posting about flashing red text and Dreamweaver!

However, playing short videos with only a few frames can be a way to draw attention to a particular part of the page; for example, if you’re browsing a clothing catalogue and one of the models moves when you hover over.

It’s worth pointing out that the entire page will be local, and so I have no network considerations whatsoever. This isn’t, however, about having three Netflix streams running at the same time – it’s short, and small videos.

The video that I’m using came from here. I’m creating an effect whereby you hover over an image of a space ship and it explodes.

MP4

It’s worth bearing in mind that most video formats are not supported by most browsers. MP4 is the exception, so it looks like this is the way to go for video encoding. I used this tool to convert the file.

Clearly this could be neater if the CSS was separated, but essentially what we have is a div element with a scaled background image, which contains a video (currently hidden). The next thing is the Javascript that plays the video:

This iterates through all the div elements and, for those that has a background image, hooks up a hover event. I’ve also assumed that the div element will be named using the format “{imagename}-video”.

Conclusion

I tried this with seven videos simultaneously, and didn’t see any jerking of the animations. Whether this would stand up under networked conditions, it’s hard to say, but with the video locally available, performance is fine.

Context

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.

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:

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:

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.

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:

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.

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:

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.

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:

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.

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.

One of the best features of Windows 8 is that it allows you to store all your contacts in one place. This means you can link your e-mail, Linked-in, Facebook, Twitter and Google+ contacts in a single list. If you want to access this programatically, it’s surprisingly simple.

The commitButtonText allows you to say what the dialog’s OK button will say. The next function is called to make the contact selection. In Windows 8 this was pickMultipleContactsAsync (there was also a pickSingleContactAsync), but both are deprecated for 8.1, and you should use the following:

// Open the picker for the user to select contacts
picker.pickContactsAsync();

Or

// Open the picker for the user to select a contact
picker.pickContactAsync();

This needs to be inside a promise, to ensure that the app doesn’t become unresponsive while you select contacts: