Posts

Showing posts with the label JavaScript

Adding Gameover and introduction screen on HTML Canvas

Image
Its been four days since my last status report. Ever since then I've been struggling trying to glue myself together and harness that for something gamedev. I've reorganized pretty much everything about the structure of the code by splitting chunks of it into bite sized modules wherever possible  and apart from that I'm proud i brought my "404" and "Gameover" sketchings to life Am looking forward to implementing main characters of the game soon. And am yet to announce everything about gameplay publicly to everybody. Here's Progress so far And gameover screen

Animated daylight on HTML5 Canvas

Image
It's Fourth day and i made improvements by adding new background Obstacle for daylight notice the wind turbines replacing trees, the sun replacing the moon and the disappearance of stars from the Sky. However it's more like day three extended++ (plus plus) trust me i've added nothing new i spent most of the time sketching introduction screens and gameover screens Here's progress so far.

Animated sky on HTML5 Canvas

Image
So far I've added a new bunch of clouds, some stars and a phase changing moon' As the number of Clouds increased i cursed them into an Array and created two more Obstacles the Moon and Stars Here's progress. (Extended preview) In extended preview i added trees and buildings. (everything is drawn programmatically without using static Images)

How to draw clouds on HTML5 Canvas

Image
So basically clouds are shapes with a flat bottom and 3 curves on top (two on the sides on bigger one on the middle) As i was creating a JS13K Game i wondered around googling if i'd find something as simple as that and 'i couldn't find anything interesting So i took some pictures of simple animated clouds and sketched it on my notepad trying to reverse engineer shapes in the figure In my first attempt i discovered that "the base is something similar to css pills, so there's rectangular shape with roundish edges and a circle overlay on top". Putting that into vanilla JavaScript i resorted to creating two canvases 1. foreground layer 2. background layer Clouds are drawn using a solid color formed by four shapes 3 circles and a rectangle then using some alpha the resultant image is then overlay-ed onto the primary canvas. Here's an example It's a sneaky way todraw clouds so they got to be a cleanway todo this without Jumping extra hoops Last reso

Introduction to webshare API (navigator.share)

Image
navigator.share is a JavaScript API providing a sharing interface similar to native apps webshare API is supported on most updated mobile browsers Including Google chrome for Android Sharing is done by passing an Object with parameters "url", "text" or "title" to navigator.share function. For a webshare request to succeed you must supply at lest one of the parameters navigator.share returns a Promise upon being called "upon navigator.share({     "url": document.location,     "text": "I'm an example",     "title": document.title }) .then(resp => console.info("Successfully shared")) .catch(errors => console.error(errors))

HTML minifier module for Nodejs

HTML minification is a process involving striping off unneeded, abundant or otherwise unused HTML attributes and elements without affecting the webpage appearance. minification is useful for statically genetated 'serverless' web application webpages as it delivers easy to digest minimal webpages html-minifier is free and open-source npm nodejs module written in JavaScript for minifying HTML documents, as compared to similar nodejs html minification modules html-minifier proves to be pretty fast, flexible and efficient html-minifier module can be used to minify HTML code programmatically or alternatively you can minify HTML code using global commandline module Npm module Installation To install module in your terminal type npm i html-minifier To install commandline version of html-minifier in your terminal type npm i -g html-minifier usage: html-minifier [options] [files...] options: --remove-comments Strip HTML comments --remove-empty-attributes Remove all attri

How to remove null elements from array in JavaScript

Every now and then arrays normally tend to have null or otherwise empty elements Array filter is a specialized JavaScript function for filtering array elements found to be matching a given criteria for example; const arr = ['max', 'duke'] In order to remove duke from elements of the array you can do it as follows; arr.filter(name => (name == 'duke' ? false : true)) // returns ['max'] You can filter empty and false elements as well, using a similar syntax as done above; const arr = ['max', null, 'duke'] arr.filter(name => name) // ['max', 'duke']

How to strip out html using regular expression in JavaScript

Regular expression isn't a very viable solution for manipulating html due to the complexity of html syntax in the browser it's recommended to create dom elements, appending html source code and then manipulating it using built-in dom querySelectors that has few drawbacks especially for environments without a dom take for instance nodejs You can use regular expression replace function as; const str = "<b>John swana</b>" str.replace(/(<([^>]+)>)/ig, "") // John swana And that's it

Es6 new features summarized round up

Escmascript es2017 or better known as es16 is the edition after the famously popular es15, In this edition there are only two new additional features the exponention operator and Array.prototype.includes() function exponention operator ** Operator is a short hand method used for raising numbers to their power Its syntax is similar to native operators such as '+' Addition and '-' (minus) for subtraction Example usage Initially to raise a number to the power you would need to use math library pow function as; Math.pow({number}, {factor}) Since es2017 you can simplify the operation above down to simply as; {number} ** {factor} Example as; 5 ** 2 // Giving you 25 Array.prototype.includes () Array includes is a feature similar to a pre existing function array.indexof() as compared to array.indexof() array.includes() function notably returns a true  boolean on matched value, and false if value not matched Examples on how to use 'array.includes ()' funct

unused css rules tree shaking elimination nodejs

Unused css rules elimination process is a lot more like tree shaking done by JavaScript bundlers for instance if you're familiar with how webpack eliminates dead code as a result tree shaking generates a much smaller bundle with only essential code Purifycss is a nodejs npm open source package that eliminates unused css You can use purifycss to remove excess css from libraries such as bootstrap, materal design lite to name a few, Installation You can get "purify-css" npm package from the package manager by typing in your terminal; npm i purify-css To install globally add -g flag; npm i -g purify-css Basic example usage; You can use css purify global cli package as; Syntax; purifycss {css} {html} Important flags; -m minify output -o specify output file name For example; purifycss *.css *.html -o css.min.css Output containg minified css rules will get saved to css.min.css

How to make a Snake Game using JavaScript and html5

Image
I compiled stapes to create a game similar to Nokia developed, popular game called 'snake' Snake was first developed by Nokia, programmed in 1997 by Taneli Armanto and published on Nokia mobile devices,  It was introduced on Nokia model 6110, 3310 from 2000 and later the game was rebranded as " Snake Xenzia " Included on later mobile phone models I made a version that is more simplified and more beginners friendly, It's based on the same idea of making a snake that grows as it eats stuff and the score increases as it grows I'm implementing this whole game in pure vanilla JavaScript and a taste of html5 canvas, In this project the canvas is used as a renderer for the game's visual output concepts and initial ideas I got the idea while doing another retro gaming project, i thought it would be good too if i created this game, from start my plan had been simplicity and making this game easy to implement, So to simplify everything i had

How to create zip archives in nodejs

I'm going to compile ways in which you can create archives compressed using zip algorithm in nodejs or a similar JavaScript runtime. node-zip is an open source zip archiving utility authord by daraosn and folked from jszip capable of compresding files into a zip archive and extracting zip archives in JavaScript. node-zip is available on npm you can install it in your terminal window by typing; npm install node-zip example usage const  zip = new require('node-zip')() zip.file('test.file', 'John Swana') const data = zip.generate({base64:false,compression:'DEFLATE'}) console.log(data) How to unzip a zip archive const zip = new require('node-zip')(data, {base64: false, checkCRC32: true}) console.log(zip.files['test.file'])

How to install tfjs JavaScript library

Image
Tensorflow is a hardware accelerated JavaScript library for building, training, testing and deploying machine learning models on a JavaScript runtime environment. Installation through html script tag For use within the browser you can link to jsdelivr content delivery network using an html script tag as follows; <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script> Installation through npm package manager Alternatively you can install a self hosted version of tensorflow from npm, in your terminal type; npm install '@tensorflow/tfjs' Installation for tfjs-node on npm tensorflow has two nodejs packages made specifically for nodejs Installation for '@tensorflow/tfjs-node' This version is a cpu only version it doesn't utilize gpu to do the computing, install tfjs node by typing; npm install '@tensorflow/tfjs-node' Installation for '@tensorflow/ tfjs-node

String repeat in JavaScript

String repeat is a function that can be used to multiply a string for a given number of times, its a feature that is closely related to string multiplication operator in Python programming language, as compared to Python's syntax; ("String") * (number of times to repeat) "A" * 3 // returns "AAA" Something similar may be archived using string repeat function in JavaScript as; ("String").repeat(number Of times to repeat) For example to triple "A" you can do as; "A".repeat(3) Practical example is with lyrics; const part = "i feel you, " const lyrics = part.repeat(4) + " A, B, C" // "i feel you, i feel you, i feel you, i feel you, A, B, C" Further reading; String . prototype . repeat () MDN

Rest operator in JavaScript

Rest operator is similar to spread operator its an es6 feature that allows converting arguments to an array of values; Syntax of spread operator is as follows; function spr(...params) { console.log(params) } spr(1,2,3) // [1, 2, 3] You can use rest operator among other arguments function sprr(args, ...params) { console.log(params) } spr('foo', 1, 2, 3) // [1, 2, 3] More information: Rest parameters MDN

JavaScript String includes function

String includes is a function introduced to JavaScript in Escmascript 'es6' that returns a boolean true , or false based on the evaluation whether or not a string contains the string passed as an argument to the function For example; const str = "John swana" str.includes('John') // true str.includes('duke') // false Running string includes testing whether 'John swana' includes John returns trues as it's a fact. Running the same string against duke returns false duke is not part of the string 'str'

comparison on var, let and const variable declaration

Introduction let, const and var are keywords used for variable declarations in JavaScript programming language, const and let were newly introduced to the programming language in Escmascript es6 or es2016. Declaration keywords the syntax of declaring a variable using let keyword is done as; let {variable name} = value for const it's done as; const {variable name} = value similarly with var; var {variable name} = value Scope for 'let' and 'const' variables let and const declared variables are block scoped that means values assigned remain within the block of assignment; take for instance; if(true) {    const declaration = "declared" } console.log(typeof declaration) // undefined values remain accessible only within the if block Scope for 'var' variables var declared variables are function scoped so variables declared within a function are only accessible within the function it's self for example; function assign(param){    

Es6 destructuring operator in JavaScript

JavaScript from es6 enables destructuring operation, In JavaScript destructuring is done using the syntax; const [elements] = [array] const {properties} = {object} For instance using Math object as an example destructuring can be done as follows; Object matching syntax; const {abs, min, max} = Math; List matching syntax; const [max, min, avg] = [10, 1, 5] Fail-soft destructuring similar to object property look up returns undefined if there's no property matching; var [item] = []; item === undefined; Fail-soft destructuring can also be done with predefined default vslues as follows; var [item = 1] = []; item === 1; More information: MDN Destructuring assignment

How to write a self invoked function in JavaScript

Self invoked functions are function that run on themselves without need to be called, the syntax to create self invoked functions is as follows; (function(){ // function body })() the runtime will run everything in a self invoked function's body You can pass parameters to the function using the syntax below; (function(params){     // function body })(params) parameters will be made available to the function as any other argument

JavaScript default parameters

Image
Since es6 its possible to include default function parameters just like other programing languages such as php do, default parameters cut down the need to initially set default Parameters within the code as; const vec function (x, y){ if(typeof x == "undefined") x = 0; if(typeof y == "undefined") y = 0; return { x, y } } now the above can be done in a more simple way , using default parameters as; const vec function (x = 0, y = 0){ return { x, y } } In either of the functions if you omit either of the Parameters your parameter will default to zero ie 0;