eCharts (v3) Gauge chart

eCharts (v3) has captured my attention and am impressed. Lets create a gauge chart and also understand the code.

Note: CDN for english version of echarts version 3 can be found here :

https://cdnjs.com/libraries/echarts

HTML:

<!doctype html>
<html>
<head>
<title>Charts Gauge Example</title>
</head>
<body>
<div id="chart" style="width: 100vw; height: 100vh;">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/3.7.2/echarts-en.min.js"></script>
<script src="app.js"></script>
</body>
</html>

The js code (app.js):

var mychart = document.getElementById('chart');
 gChart = echarts.init(mychart);
 var option = {
   tooltip : {
     formatter: "{a} <br/>{b} : {c}%"
   },
   toolbox: {
     show : true,
     feature : {
       restore : {show: true},
       saveAsImage : {show: true}
    }
   },
 series : [
 { 
     title:{
         show:true,
         offsetCenter:[0,-230],
         color:'#888',
         fontWeight:'bold',
         fontSize:24 
         },
     clockwise:true,
     startAngle:180,
     endAngle:0,
     pointer:{show:true},
     axisTick:{show:true},
     splitLine:{show:false},
     name:'Business Indicators',
     type:'gauge',
     detail : {
         offsetCenter:[5,-40],
         formatter:'{value}%'
         },
     data:[{value: 75, name: 'Rate'}]
 }]
};

//Add this to have the data changed every two seconds
setInterval(function () {
 option.series[0].data[0].value = (Math.random() * 100).toFixed(2) - 0;
 gChart.setOption(option, true);
},2000);

  • Here first we are setting variable “mychart” to DOM element with ID = “chart”
  • At line 2 of the JS we initialize an echart at the DOM ID (“chart”)
  • Now we set the options which will be passed to the initialized echart to render on screen

Decoding the “options”:

  • In the example , options has the following attributes
    • series
    • tooltip
    • toolbox

Series:

Here we define the

  • name of chart – ‘Business Indicators’ in the example
  • type of chart – ‘Gauge’
  • Title (“Rate” in this example)  takes its value from data.name and the styling is driven by series.title properties 
  • startAngle is 180 and endAngle is 0 (see pic) when property clockwise is set to true (default)
  • series.data.value is displayed with style and positioning defined by series.details
  • pointer and axis ticks have visbility set to true.

 

Tooltip:

  • Here we define the content to be seen when hovering over the pointer.
  • In line 33 of JS code ,
    • {a} represents name of the chart, defined in property series.name (“Businesss Indicators”)
    • {b} represents data.name
    • {c} represents data.value

Note : There are more options to customize ( described in API documentation of echarts)

Tool Box:

  • Here two features are defined to be visible -> Restore and Download as Image.
  • There are other options that can be configured

Heres the output:

Just by changing the startAngle and/or endAngle you can change the shape of the dial.

Ex, set startAngle to 225 and endAngle to -45 and here’s what you get:

 

Posted in Charts n Graphs, Generic, JS Frameworks, Web Technology

eCharts (v3) Simple Bar Chart

I have been playing around with javascript based charting libraries. I like HighCharts. Its pretty good for the charts you will need with very good customization features. It, however it is not free (for commercial uses).

D3 library is good for creating your own charting solutions and there are a pretty good charting libraries out there built on top of D3. Personally am a big fan of the D3 library and Mike Bostock.

However recently I came across eCharts (version 3) (owned by Baidu) and was blown away by the examples in its gallery. Its based on ZRender which is a lightweight canvas library.

Its definitely something I will use over highcharts in my next project.

Here’s a list of things that made me try it :

  • A very rich gallery where you can play around as well -> Demo Gallery
  • Canvas based*
  • Very well documented -> API Docs
  • It also has a offline chart builder.
  • Free. Yes you can simply get the minified js and start using it.

Note : A lot of people indicated that the documentation is difficult as it is mostly in chinese. As of today I did not find that to be a hindrance and the documentation I read was in plain English.

Here’s the CDN for the english version of echarts version 3

https://cdnjs.com/libraries/echarts

Do give it a try.

Here’s a sample application :

The js code (app.js):

var chartdata=[
 {    
     name: 'Oranges',    
     type: 'bar',    
     data: [20, 20, 36, 12, 15, 20]    
 },          
 {    
     name: 'Apples',    
     type: 'bar',    
     data: [8, 5, 25, 10, 10, 13]    
 },
 {    
     name: 'Strawberries',    
     type: 'bar',    
     data: [8, 5, 20, 10, 7, 15]    
 },          
 {    
     name: 'Mangoes',    
     type: 'bar',    
     data: [8, 5, 20, 10, 7, 15]    
 }
];

var legendData = chartdata.map(function(d){return d.name;});

var chart = document.getElementById('chart');    

var myChart = echarts.init(chart);  
  
var option = {    
               title: { 
                        text: 'eCharts:Bar',                 
                        textStyle:{                          
                                    color:'#fff'                  
                                   }
                       },
               toolbox: {
                         show : true,
                         feature : {            
                                     dataView : {show: true, title:'Data View', readOnly: false},            
                                     magicType : {show: false, title:['line','bar'],type: ['line', 'bar']},            
                                     restore : {show: true, title:'Restore'},            
                                     saveAsImage : {show: true, title:"Save As Image"}        
                                    }    
                        },    
               tooltip: {                   
                         backgroundColor:'rgba(250,250,250,0.7)',                  
                         textStyle:{                              
                                     color:'#000'                              
                                   }                                     
                         },
               legend: { 
                         orient:'vertical',                   
                         textStyle:{                              
                                     color:'#fff'                              
                                   },                   
                         left:'30',
                         top:'100',           
                         data: [ 'Oranges','Apples','Strawberries','Mangoes' ]
                        },
               xAxis: { 
                        data: [ "2006", "2008", "2010", "2012", "2014", "2016" ]
                       },    
               yAxis: { },    
               series: chartdata,          
               backgroundColor:'rgba(0, 0, 0, 1)',          
               textStyle:{
                           color:'#fff'          
                },          
               color:[ '#FF9800','#ef5350','#F48FB1','#81C784','#c4ccd3','#c23531','#2f4554','#61a0a8','#d48265','#91c7ae']
};
myChart.setOption(option);

The HTML Code(index.html):

<!doctype html>
<html>
<head>
<title>Charts BarChart Example</title>
</head>
<body>
<div id="chart" style="width: 100vw; height: 100vh;">
</div>
<script src="http://echarts.baidu.com/dist/echarts.min.js"></script>
<script src="app.js"></script>
</body>
</html>

And here’s the output (Its interactive and you can toggle the series via the legends) :

 

 

Github repo : https://github.com/nizantz/echartsDemo.git

Codepen link : https://codepen.io/nizantz/full/QqgVmZ/

Pretty interesting. I will be playing around more with echarts and vue.

Posted in Charts n Graphs, Generic, JS Frameworks, Web Technology

Switch to Yarn (from npm)

I switched to yarn from npm cause it does everything that npm does (almost everything and more) , only faster.

And by faster I mean, really really fast, like ultrafast.

What is yarn, anyways?
Its a package manager for your code (just like npm) from Facebook.


How to install yarn on your OSX?
brew install yarn
This will also install node.

Use this if you want to skip installing node.
brew install yarn --without-node

You could also use npm itself to install yarn ( and then switch to yarn completely )
npm i -g yarn


If you are already familiar with npm heres a list of commands that can help you switch to yarn faster:

here will be a table

Example of “yarn why <package>”

Pretty useful command to get package details and info

nsingh$ yarn why babel-core
yarn why v0.27.5
[1/4] Why do we have the module "babel-core"...?
[2/4] Initialising dependency graph...
[3/4] Finding dependency...
[4/4] Calculating file sizes...
info Has been hoisted to "babel-core"
info Reasons this module exists
- "babel-core#babel-register" depends on it
- Specified in "devDependencies"
info Disk size without dependencies: "228kB"
info Disk size with unique dependencies: "8.25MB"
info Disk size with transitive dependencies: "17.06MB"
info Number of shared dependencies: 28
Done in 0.91s

Screenshot of “yarn upgrade-interactive v0.27.5 “

 

 

 

 

 

 

Speed Test : npm vs yarn

npm install took 26 secs

yarn install tool 9.95 secs

(Note : I will be updating this page as and when needed)

 

 

Posted in Generic, Web Technology

Scaffolding Vue Projects – Webpack Template

In this post we will initialize a project using the webpack template (provided out of the box by vuejs.org)

This post assumes that you already have the vue-cli installed.
[ See the previous post if not – > http://www.knowstack.com/scaffolding-vue-projects-simple-template/]

Now we initialize a project using the webpack template:

vue init web pack vue_webpack_demo

Next step is to install the dependencies using npm or yarn (Yarn was much faster):

npm install

OR
yarn install

nsingh$ yarn install
yarn install v0.27.5
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
Done in 7.15s.

Once done , start the dev server:

npm start

OR
yarn start

This will launch the app in your browser:

You can open the project in your favorite IDE ( am using atom)  and start adding/modifying content and see the updates immediately in your browser window:

So we have a vue project with webpack template ready to go and work on.

 

Posted in Generic, HTML5, JS Frameworks, VueJS, Web Technology Tagged with: , ,

Scaffolding Vue Projects – Simple Template

In this post we will setup a vue-cli for scaffolding due projects.

First things first , install vue-cli

At the time of writing this , to install vue-cli you need :

  • Node installed (works with version >4.x)
  • npm version 2+
nsingh$ node -v
v4.2.1
nsingh$ npm -v
2.14.7

Now install the CLI:

sudo npm install -g vue-cli

Now we initialize a project. The command to use is :

vue init <template-name> <project-name>

Vue provides the following scaffolding templates:

  • webpack – A full-featured Webpack + vue-loader setup with hot reload, linting, testing & css extraction.
  • webpack-simple – A simple Webpack + vue-loader setup for quick prototyping.
  • browserify – A full-featured Browserify + vueify setup with hot-reload, linting & unit testing.
  • browserify-simple – A simple Browserify + vueify setup for quick prototyping.
  • pwa – PWA template for vue-cli based on the webpack template
  • simple – The simplest possible Vue setup in a single HTML file

Custom templates can also be used ( Read here : vue-cli)

Lets start with the simple template :

nsingh$ vue init simple simple_demo

This will ask a couple of questions (like name and author) and we can go with the default answers.

? name simple_demo
? author **Nishant**::
vue-cli · Generated "simple_demo".

Now go to the folder and see the folder structure:

nsingh$cd simple_demo
nsingh$tree 
.
└── index.html

Note : command “tree” can be installed on mac OS using:   brew install tree

Now you can open the code in your favorite editor (Would recommend atom or sublime ) and launch the code in browser:

This will launch on http://127.0.0.1:3000 (Default port on atom-live-server)

And the output can be seen.

So the “simple” template added the index.html with links to the vue js script and ready for exploring vue.

Next we will learn on using the webpack template.

Posted in Generic, JS Frameworks, VueJS, VueJS, Web Technology

Basic Vue JS Dev Setup

I have been lately exploring Vue JS and am fascinated with its simplicity. In this post am describing how to get started in setting up a simple dev environment.

I would recommend atom editor with its live server. Frankly any IDE would work.

  1. Simple setup : Include the vue js script directly
    • Download the vuejs dev version (recommended for dev) from  https://vuejs.org/js/vue.js

OR

    • Use CDN from (Recommended) : https://unpkg.com/vue as it points to the latest version as soon as published to npm

Sample code using CDN:

<!DOCTYPE html>
<html><head> 
  <title>Vue List</title>
</head>
<body> 
  <div id="app">     
    <ul>NOT PRIMARY       
      <li v-for="i in colors" v-if=!(i.primary)>{{ i.color }} 
    </ul>     
    <ul>PRIMARY       
      <li v-for="i in colors" v-if=i.primary>{{ i.color }}     
    </ul>   
  </div> 
  <script src="https://unpkg.com/vue"></script> 
  <script>
    let app = new Vue({ el:'#app',
                      data:{
                            colors:[
                                     {color:'red',primary:true},
                                     {color:'orange',primary:false},
                                     {color:'yellow',primary:true},
                                     {color:'green',primary:false},
                                     {color:'blue',primary:true},
                                     {color:'indigo',primary:false},         
                                     {color:'violet',primary:false}  
                                    ]     
                            }   
                       }); 
  </script>
</body>
</html>

Sample code using downloaded vuejs :

<!DOCTYPE html>
<html><head> 
  <title>Vue List</title>
</head>
<body> 
  <div id="app">     
    <ul>NOT PRIMARY       
      <li v-for="i in colors" v-if=!(i.primary)>{{ i.color }} 
    </ul>     
    <ul>PRIMARY       
      <li v-for="i in colors" v-if=i.primary>{{ i.color }}     
    </ul>   
  </div> 
  <! For DEV - Unminified and Debug on version -->
  <script src="lib/dev/vue.js"></script> 
  <! For PROD - Minified and Debug off version -->
  <!--<script src="lib/prod/vue.min.js"></script> -->
  <script>
    let app = new Vue({ el:'#app',
                      data:{
                            colors:[
                                     {color:'red',primary:true},
                                     {color:'orange',primary:false},
                                     {color:'yellow',primary:true},
                                     {color:'green',primary:false},
                                     {color:'blue',primary:true},
                                     {color:'indigo',primary:false},         
                                     {color:'violet',primary:false}  
                                    ]     
                            }   
                       }); 
  </script>
</body>
</html>

Thats pretty much for a basic setup and jumping right in to explore vuejs.

Its also recommended to install  – Vue.js devtools Chrome extension

Next article will talk about setting up vue-cli and scaffolding a vue project.

Posted in Generic, VueJS

Basic React Dev setup using npm or yarn and webpack

Setting Up ReactJS Environment

Heres a basic react js dev setup (Level : Beginner)

 Create a directory and go to the root of the directory

mkdir my-react-dir

cd my-react-dir

Install npm

brew install npm  // installs node

or  you can download it directly from NodeJS.org

If Yarn is what you like then ←

Install Yarn

brew install yarn  // installs node

brew install yarn --without-node

Initialize Package.json

npm init

OR

yarn init

Go with the default options.

cat package.json

{  "name": "react-environment",   
   "version": "1.0.0",   
   "description": "",   
   "main": "index.js",   
   "scripts": {},   
   "author": "",   
   "license": "ISC" 
}

Install webpack and webpack-dev-server using npm or yarn

npm install webpack webpack-dev-server --save-dev

OR

yarn add webpack webpack-dev-server  -D

Add an index.html

touch index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React Environment Setup</title>
</head>
<body>
    <h3>Setting the React Env</h3>
    <div id='app'></div>
    <script type="text/javascript" src="bundle.js"></script>
</body>
</html>

Add an index.js file

mkdir app

cd app

touch index.js

Add to index.js this single line

//index.js
console.log("Hello React");

Configure WebPack

module.exports = {
    entry: ['./app/index.js'],
    output: {
        filename: 'bundle.js'
    }
};

Install and set Babel dependencies

npm install babel-core babel-loader babel-preset-env --save-dev

OR

yarn add babel-core babel-loader babel-preset-env -D

  • babel-core and babel-loader is the dependency, which transpile the ES6 code to ES5
  • Use babel-preset-env instead of babel-preset-es2015. babel-preset-env let us use some advanced feature of ECMAScript in our web applications.

Update package.json

 {
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
"build": "webpack-dev-server"
},
  "author": "",
  "license": "ISC"
}

Update WebPack config:

module.exports = {
    entry: ['./app/index.js'],
    output: {
        filename: 'bundle.js'
    },
module: {
        loaders: [
            {
                loader: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/
            }
        ]
    },
devServer:{
port:9000
}
};

Run the dev server

npm run build

OR

yarn build

This will run the build script defined in package.json which internally will invoke web pack dev server . 

App will be up on http://localhost:9000/

Install and configure React and ReactDOM

We would also need to get the package called “babel-preset-react” and “babel-preset-stage-3” to use latest ES6 features and to write react code in ES6 syntax

npm install --save react react-dom

OR

yarn add react react-dom

npm install babel-preset-react babel-preset-stage-3 --save-dev

OR

yarn add babel-preset-react babel-preset-stage-3 -D

The package.json should look like this :

{
  "name": "react-environment",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",
    "webpack": "^3.6.0",
    "webpack-dev-server": "^2.8.2"
  },
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  }
}

Create a file .babelrc in root directory and add the following to it:

{
  "presets": ["env", "react", "stage-3"]
}

Create a component file App.js inside components folder 

cd app

mkdir components

touch app.js

Add the following to app.js

//app.js
import React, { Component } from 'react';
export default class MyApp extends Component {
    render(){
        return (
            <div>
                The React Env is now set. Served from react component.
            </div>
        );
    }
}

Import App.js file into index.js file

//index.js
//console.log("Hello React");
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(<App />, document.getElementById('app'));

 

Now just run the dev server (npm build or yarn build)  and launch http://localhost:9000 in your browser

This is a basic react dev setup to get started and going.

You could add rules to your web pack for minification, compression and all.

Personally I found Yarn (from Facebook) to be much faster than npm for installing node modules.

Posted in Generic, Web Technology

Swift CAReplicatorLayer Sample Code

Created By: Debasis Das (29-May-2017)
In this post we will see how CAReplicatorLayer works and create a couple of sample code to play around with CAReplicatorLayer
CAReplicatorLayer is essentially a layer that creates a specified number of copies of its sublayers, each copy potentially having geometric, temporal, and color transformations applied to it.

We can use a CAReplicatorLayer object to build complex layouts based on a single source layer that is replicated with transformation rules that can affect the position, rotation color, and time.

In this post we will create the below samples
Swift_CAReplicatorLayer_Nesting_1
Swift_CAReplicatorLayer_Nesting_2
Swift_CAReplicatorLayer_ProgressIndicator_1
Swift_CAReplicatorLayer_ProgressIndicator_2
Swift_CAReplicatorLayer_ProgressIndicator_3
Read more ›

Posted in Swift, Swift 3.1 Tagged with: , ,

Swift Mac OS Animation using Animator Proxy – Part 2

In continuation to the Swift Mac OS Animation Part 1 we will work with Animator Proxy to achieve animation in Mac OS Applications.

Animator Proxy
Some simple Mac OSX Animation can be achieved through the usage of Animator Proxy. Animator proxy is the quickest and easiest way to implement animation effects in views and windows.
The animations caused by using animator proxy is called as Cocoa Animation or Cocoa Animatable Proxy Animation. Animator proxy provides a benefit to achieve animations without using core animation layers.

The way animator proxy works is rather than an UI object changing its own size or origin asks the animator proxy to change its properties values using an animation effect

Swift-AnimatorProxy
Read more ›

Posted in Swift, Swift 3.1 Tagged with: , ,

Swift Mac OS Animation using Core Animation- Part 1

Created By: Debasis Das (27-May-2017)
Swift Mac OS Animation
Animation in Mac OSX has a long history and there are more than one option for achieving an animated behavior in a Mac Application.

We can achieve animation in a Mac Application using
1. Simple View Animation
2. Using Animation Proxy or
3. Using Core Animation on CALayer

The above animation techniques can be used in isolation or it can be merged with each other to achieve a certain animation behavior

The decision to use one approach vs the other purely depends on the animation complexity and the degree of control that is desired. Whether user interaction is desired on the screen that has animated layers etc.

If a simple animation such as animating the size of the NSWindow is required, it would be easier to simply use an animator proxy to achieve the functionality, however if we have complex requirement of creating a firework effect, we would need to look beyond View Animation or using an animator proxy.

In this post we will see how Core Animation works in Mac OSX.
CAAnimation is the abstract superclass for all Core Animations.
CAAnimation has the following subclasses
– CABasicAnimation
– CAKeyframeAnimation
– CAAnimationGroup
– CATransition

We can animate the contents of our applications by attaching animations (Stated above) with Core Animation Layers

CABasicAnimation

  • Provides basic single-keyframe animations to the CALayers properties.
  • While initializing a CABasicAnimation we state the keypath of the property that we want to animate.
  • The property can be the backgroundColor, it can be the layer opacity or border color etc.
  • The animation has a from and a to value that need to be stated.
  • for example, we can animate the color change of a CALayer from red to green by creating a CABasicAnimation with backgroundColor keypath and then state the fromValue as red and toValue as green

CAKeyframeAnimation

  • Is similar to CABasicAnimation with a difference that it can accept multiple intermediate values and multiple intermediate keyTimes that controls how the transition happens
  • The timing and pacing of keyframe animations are complex than the basic animations.
  • There is a property of CAkeyframeAnimation called as calculationMode which defines the algorithm of the animation timing.
  • Below are the calculation modes
    • kCAAnimationLinear – provides a linear calculation between keyframe value
    • kCAAnimationDiscrete – each keyframe value is used in turn and no interpolated values are calculated.
    • kCAAnimationPaced – Linear keyframe values are interpolated to produce an even pace throughout the animation.
    • kCAAnimationCubic – Smooth spline calculation between keyframe values
    • kCAAnimationCubicPaced – Cubic keyframe values are interpolated to produce an even pace throughout the animation.
  • The decision of the calculationMode plays a key role based on what type of animation we are trying to achieve. A bouncing ball effect would require the ball to fall at a slow speed initially and gradually the speed should increase and when it hits the ground it should bounce back with initial higher speed and the speed should taper at the top before it reverses direction.

CAAnimationGroup

  • Allows multiple animations to be grouped and run concurrently.
  • We can create multiple animations using CABasicAnimation or CAKeyframeAnimation each having a different animation duration and then we can create a CAAnimationGroup using an array of individual animations.
  • The CAAnimationGroup also has a duration property which if smaller than individual animation durations will clip the individual animation durations.

Using a combination of CABasicAnimation, CAKeyframeAnimation and CAAnimationGroup we can achieve amazing animation effects.

We will progress through to create the below animation effect
SwiftGroupedAnimation
Read more ›

Posted in Swift, Swift 3.1 Tagged with: , , , , ,

Hit Counter provided by technology news