Categories
JavaScript

Add Charts to Our JavaScript App with Anychart — Bubble, Bullet, and Column Charts

Anychart is an easy to use library that lets us add chart into our JavaScript web app.

In this article, we’ll look at how to create basic charts with Anychart.

Bubble Charts

We can create bubble charts easily with Anychart.

For instance, we can write the following HTML:

<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-base.min.js" type="text/javascript"></script>
<div id="container" style="width: 500px; height: 400px;"></div>

Then we can write the following JavaScript code:

const chart = anychart.cartesian();
const data = [
  ["2000", 1100, 1],
  ["2001", 880, 2],
  ["2002", 1100, 5],
  ["2003", 1500, 3],
  ["2004", 921, 3],
];

chart.bubble(data);
chart.title("Bubble Chart");
chart.xAxis().title("Years");
chart.yAxis().title("Sales");
chart.container("container");
chart.draw();

The script tag is for adding the Anychart library.

The div is the container for rendering the chart.

anychart.cartesian lets us create a chart.

The data is in the data array.

The first value of each entry is the x-axis value.

The 2nd value is the y-axis value.

The 3rd is the radius of the bubble.

chart.bubble takes the data we’re rendering.

chart.title sets the title.

chart.xAxis().title sets the x-axis label.

chart.yAxis().title sets the y-axis label.

chart.container sets the ID of the container element to render the chart in.

chart.draw draws the chart.

Bullet Chart

To create a bullet chart, we write the following HTML:

<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-base.min.js" type="text/javascript"></script>
<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-bullet.min.js"></script>

<div id="container" style="width: 500px; height: 400px;"></div>

We need to add a library for creating the bullet chart via the 2nd script tag.

Then we can create the chart by writing:

const chart = anychart.bullet([{
  value: 630
}]);
chart.range().from(0).to(750);
chart.layout('vertical');
chart.container("container");
chart.draw();

We call anychart.bullet to create the chart.

chart.range has the value range for the chart.

chart.layout has the orientation of the bar.

chart.container sets the ID of the container element to render the chart in.

chart.draw draws the chart.

Column Chart

We can create a column chart by writing:

const data = [
  ["apple", 100],
  ["orange", 120],
  ["grape", 130],
];

const chart = anychart.column();
const series = chart.column(data);
chart.container("container");
chart.draw();

anychart.column create the column chart.

chart.column takes the data for the chart.

The rest of the code is the same as the previous examples.

We can set the fill color of the columns.

For instance, we can write:

const data = [
  ["apple", 100],
  ["orange", 120],
  ["grape", 130],
];

const chart = anychart.column();
const series = chart.column(data);
series.normal().fill("#0066cc");
series.hovered().fill("#0066cc", 2);
series.selected().fill("#0066cc", 4);
chart.container("container");
chart.draw();

We set the fill color of the bars with the fill method for in response to various actions.

Also, we can set the outline color in response to various actions with the stroke method:

const data = [
  ["apple", 100],
  ["orange", 120],
  ["grape", 130],
];

const chart = anychart.column();
const series = chart.column(data);
series.normal().stroke("#0066cc");
series.hovered().stroke("#0066cc", 2);
series.selected().stroke("#0066cc", 4);
chart.container("container");
chart.draw();

And the hatchFill method lets us add a hatched background to the columns:

const data = [
  ["apple", 100],
  ["orange", 120],
  ["grape", 130],
];

const chart = anychart.column();
const series = chart.column(data);
series.normal().hatchFill("forward-diagonal", "#0066cc", 1, 15);
series.hovered().hatchFill("forward-diagonal", "#0066cc", 1, 15);
series.selected().hatchFill("forward-diagonal", "#0066cc", 1, 15);
chart.container("container");
chart.draw();

Conclusion

We can add bubble charts, bullet charts, and column charts with Anychart.

Categories
JavaScript

Add Charts to Our JavaScript App with Anychart — Area, Bar, and Box Charts

Anychart is an easy to use library that lets us add chart into our JavaScript web app.

In this article, we’ll look at how to create basic charts with Anychart.

Area Chart

We can add area charts with Anychart.

To add one, we write the following HTML:

<script src="https://cdn.anychart.com/releases/8.9.0/js/anychart-base.min.js" type="text/javascript"></script>
<div id="container" style="width: 500px; height: 400px;"></div>

And the following JavaScript code:

const data = [
  ["January", 100],
  ["February", 120],
  ["March", 180],
  ["April", 110],
  ["May", 90]
];

chart = anychart.area();
const series = chart.area(data);
chart.container("container");
chart.draw();

We add the Anychart base package with the script tag.

The div is the container for rendering the chart.

The JavaScript code has the data array with the data.

The first value of each entry is the x-axis value.

And the 2nd value is the y-axis value.

Then we call anychart,area to create the area chart.

chart.area takes the data.

chart.container sets the id value of the container to render the chart in.

And chart.draw draws the chart.

We can change the series fill color with the normal , hovered , and selected methods:

const data = [
  ["January", 100],
  ["February", 120],
  ["March", 180],
  ["April", 110],
  ["May", 90]
];

chart = anychart.area();
const series = chart.area(data);
series.normal().fill("#00cc99", 0.3);
series.hovered().fill("#00cc99", 0.1);
series.selected().fill("#00cc99", 0.5);
chart.container("container");
chart.draw();

Then we see the color when the chart series is hovered over or selected.

Bar Chart

We can add bar charts with Anychart.

To add a bar chart, we call the chart.bar method:

const data = [
  ["January", 100],
  ["February", 120],
  ["March", 180],
  ["April", 110],
  ["May", 90]
];

chart = anychart.bar();
const series = chart.bar(data);
chart.container("container");
chart.draw();

anychart.bar creates the chart.

chart.bar adds the data for the bar chart.

chart.container sets the ID of the container element to render the cheat in.

And chart.draw draws the chart.

The HTML is the same as the previous example.

We can also set the fill color the same way.

Box Chart

To create a box chart, we write:

const data = [{
    x: "1",
    low: 1000,
    q1: 1050,
    median: 1200,
    q3: 1800,
    high: 2000,
    outliers: [800, 2500, 3200]
  },
  {
    x: "2",
    low: 2500,
    q1: 3000,
    median: 3800,
    q3: 3900,
    high: 4000
  },
  {
    x: "3",
    low: 2000,
    q1: 2300,
    median: 2500,
    q3: 2900,
    high: 3000
  },
  {
    x: "4",
    low: 4000,
    q1: 5000,
    median: 6500,
    q3: 6500,
    high: 7000,
    outliers: [8930]
  },
  {
    x: "5",
    low: 8000,
    q1: 8400,
    median: 8500,
    q3: 8800,
    high: 9000,
    outliers: [6950, 3000]
  }
];

const chart = anychart.box();
const series = chart.box(data);
chart.container("container");
chart.draw();

low is the low value.

q1 has the 1st quantile value.

median has the median value.

q3 has the 3rd quantile value.

high has the highest value.

outliers has the outlier values.

Then we create the box chart with the anychart.box method.

chart.box takes the data for rendering the chart.

Conclusion

We can create area charts, bar charts, and box charts easily with Anychart.

Categories
React

Using Bit.dev with Gatsby

Bit.dev is a great snippet repository to let us add store our front end components as standalone packages.

In this article, we’ll take look at how to add create component packages that are created for Gatsby and then use them in another Gatsby project.

Build a Gatsby Landing Page

The first step is to build a simple landing page component in our first Gatsby project. Then we’ll extract that component from it with the Bit CLI later and import it to the other Gatsby project and use it.

Make sure that we use recent version of Node like 10.x or later before we run anything.

First, we’ve to install the Gatsby CLI by running:

npm install -g gatsby-cli

Then we create a new Gatsby project by running:

gatsby new gatsby-landing-page

Once we did that, we start our development server by running:

gatsby develop

Next, we create a landing-page folder in the components folder and then create and index.js and banner.jpg file inside it.

We have to do so we can export the whole folder as a package with Bit CLI later.

The root JavaScript file must be called index.js. Then we put in the following code into index.js:

import React from "react"
import BannerImage from './banner.jpg'

const LandingPage = () => {
  return (
    <div className='center'>
      <h1 >Buy Now</h1>
      <p>Use Bit to store your code now.</p>
      <div style={{ maxWidth: `100vw`, marginBottom: `1.45rem` }}>
        <img src={BannerImage} alt='landing page image' />
      </div>
      <button>Subscribe to Bit Now</button>
    </div>
  )
}

export default LandingPage

We have to import the image file directly since we can’t use the GraphQL hooks in a compiled package since the GraphQL queries are run at compile time.

If we use the useStaticQuery hook to include our image, we’ll get an error is we import it later.

Next, we create our own Layout component by creating the layoutcomponent folder in the components folder.

Then we create index.js in there and add the following:

import React from "react"
import Header from "../header"
import "./layout.css"

const Layout = ({ children, title }) => {
  return (
    <>
      <Header siteTitle={title} />
      <div
        style={{
          margin: `0 auto`,
          maxWidth: 960,
          padding: `0 1.0875rem 1.45rem`,
        }}
      >
        <main>{children}</main>
        <footer>
          © {new Date().getFullYear()}, Built with
          {` `}
          <a href="https://www.gatsbyjs.org">Gatsby</a>
        </footer>
      </div>
    </>
  )
}

export default Layout

We move the layout.css file from the generated code into the layoutfolder.

In index.js in the pages folder, we replace what we have with:

import React from "react"
import LandingPage from '../components/landing-page';
import Layout from "../components/layout"
import SEO from "../components/seo"

const IndexPage = () => (
  <div className='center'>
    <Layout title='Buy Now'>
      <SEO title="Home" />
      <LandingPage />
    </Layout>
  </div>
)

export default IndexPage

‘Export’ (Publish) All Reusable UI Components From the Project to Bit.dev

Now that we created our Gatsby landing page in the gatsby-landing-page project. We can export it now to the Bit.

First, we go to bit.dev to create an account.

Then we have to log into it and then create a collection. We can click the ‘+New’ button on the top right, then click Collection to do that.

When we’re asked for the name, enter ‘landing-page’. We’ll leave it public for this example, but it can also be private.

Next, we go to the command line to install the Bit CLI by running:

npm install bit-bin -g

To check that it’s installed, we run:

bit --version

Then we log into the Bit account we just created by running:

bit login

It’ll configure itself automatically. If we want to check the settings that were configured, we can run:

bit config

It’ll add the NPM registry used the Bit to our .npmrc file automatically.

Next, we run bit init to initialize Bit in our gatsby-landing-pageproject.

Then we’ll get a new .bitmap file in our project’s root directory. It tacks Bit components an only includes a comment and line with out Bit version.

In package.json, we’ll see something like the following included:

"bit": {
    "env": {
        "compiler": "bit.envs/compilers/react@1.0.16"
    },
    "componentsDefaultDirectory": "components/{name}",
    "packageManager": "npm"
}

Now we’re ready to build and upload our component files to Bit.

In the command line, we change to our project’s root folder and run:

bit add src/components/landing-page
bit add src/components/header
bit add src/components/layout

Then we’ll see our files added by Bit. We can run bit status to see if it’s been added successfully.

Now we have to install the Bit React compiler by running:

bit import bit.envs/compilers/react --compiler

so that we can build the package and then upload the built package to Bit.

Building the components makes sure that the component is directly consumable by other project and also that the component includes all rthe parts that are required in order to share it with others.

Now we can build the project by running:

bit build

Once we did that, we can tag it with a version number by running:

bit tag --all 0.0.1

We can check the status of tagging by running bit status.

Now we can upload our component to Bit by running:

bit export <username>.landing-page

This will compile and push the component to Bit.

Now when we run bit status, we should see nothing to tag or export since we pushed our built package to Bit.

We can then check what’s uploaded with bit list. To preview our component, we can go to https://bit.dev/<username>/landing-page/landing-page

Create a new Gatsby project.

Now that we uploaded our landing page component to Bit, we can use it in another project.

In this example, we’ll use it in another Gatsby project.

To create a new Gatsby project, we run:

gatsby new gatsby-bit-dev

Import reusable UI components from Bit.dev (the same components you’ve published from the first landing page).

After we created our Gatsby project, we go to the directory for our project and then we have to add the Bit registry to our project by running:

npm config set @bit:registry https://node.bit.dev

since we left our component public. If we make our component private in Bit, we have to run:

npm login --registry=https://node.bit.dev --scope=@bit

Our component package will be available in the @bit/<username>.<collection name>.<component name> format.

There in our example, we’ll run:

npm install @bit/jauyeunggithub.landing-page.landing-page --save

npm install @bit/jauyeunggithub.landing-page.header --save

npm install @bit/jauyeunggithub.landing-page.layout --save

After we run that, we’ll see that we have:

"@bit/jauyeunggithub.landing-page.landing-page": "0.0.1",

in package.json of our gatsby-bit-dev project.

Importing and Using Our Component.

In the components folder, add subscribe-button.js and add:

import React from "react"

const SubscribeButton = () => <button>Subscribe to Newsletter</button>

export default SubscribeButton;

Now to use it, we go to index.js and add:

import React from "react"

import Layout from '@bit/jauyeunggithub.landing-page.layout';
import SEO from "../components/seo"

import LandingPage from '@bit/jauyeunggithub.landing-page.landing-page';
import SubscribeButton from "../components/subscribe-button";

const IndexPage = () => (
  <Layout>
    <SEO title="Home" />
    <LandingPage />
    <div className='center'>
      <SubscribeButton />
    </div>
  </Layout>
)

export default IndexPage

In the code above, we imported our landing page component package that we published to Bit and then referenced it.

We used the SubscribeButton component from our project and the rest of the components are imported from Bit.

Now when we run gatsby develop --port 8001, we’ll see the same landing page as we seen before.

Conclusion

Bit provides us with an easy way to publish Gatsby React component to a central place so that we can use them later,

It just takes a few command to compile a series of components inside one folder into a package and then import it in another project.

To import the package, we just have to add the Bit NPM registry by using npm config and then we can install our package like any other Node package and use it.

Categories
Vue 3 Projects

Add an Audio Player with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a video player with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create audio-player

and select all the default options to create the project.

Create the Audio Player

We can create the audio player by writing:

<template>
  <input
    type="range"
    min="0"
    max="100"
    step="1"
    v-model="seekValue"
    @change="onSeek"
  />
  <audio
    src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
    ref="audioPlayer"
    @timeupdate="onPlaying"
  >
    Your browser does not support the
    <code>audio</code> element.
  </audio>
  <p>{{ currentTime }}</p>
  <div>
    <button @click="play">play</button>
    <button @click="pause">pause</button>
    <button @click="stop">stop</button>
    <button @click="setSpeed(0.5)">0.5x</button>
    <button @click="setSpeed(1)">1x</button>
    <button @click="setSpeed(1.5)">1.5x</button>
    <button @click="setSpeed(2)">2x</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      currentTime: 0,
      seekValue: 0,
    };
  },
  methods: {
    play() {
      this.$refs.audioPlayer.play();
    },
    pause() {
      this.$refs.audioPlayer.pause();
    },
    stop() {
      const { audioPlayer } = this.$refs;
      audioPlayer.pause();
      audioPlayer.currentTime = 0;
    },
    setSpeed(speed) {
      this.$refs.audioPlayer.playbackRate = speed;
    },
    onPlaying() {
      const { audioPlayer } = this.$refs;
      if (!audioPlayer) {
        return;
      }
      this.currentTime = audioPlayer.currentTime;
      this.seekValue = (audioPlayer.currentTime / audioPlayer.duration) * 100;
    },
    onSeek() {
      const { audioPlayer } = this.$refs;
      const seekto = audioPlayer.duration * (this.seekValue / 100);
      audioPlayer.currentTime = seekto;
    },
  },
};
</script>

We have a range input that we can slide around to change the seekValue ,

We bound it to seekValue with v-model .

Also, we attach a change event handler to the input that changes the currentTime of the audio element to seek the audio.

The audio element has the audio we want to play.

We listen to the timeUpdate event so we can get the current time.

We assign a ref to it so we can manipulate it later.

Below that, we display the currentTime .

And then we have a few buttons to let us play, pause, stop, and change the speed of the audio.

Below the template, we have the data method with the currentTime and seekValue reactive properties returned.

The play method gets the audio player element from the ref and call play to play the audio.

The pause method gets the audio player element from the ref and call pause to pause the audio.

The stop method pauses the audio and set the currentTime to 0 to reset the audio playback back to the beginning.

setSpeed lets us set the speed by changing the playbackRate property.

The onPlaying method is called when the timeUpdate event is emitted.

We set the this.currentTime reactive property to the currentTime property of the audioPlayer .

Also, we update the seekValue so that it’s in sync with the currentTime .

This will update the range slider to be in sync with the currentTime .

Finally, we have the onSeek method that’s run when the change event is emitted by the range input, which is done when we’re done moving the slider.

We get the seekValue reactive property and to compute the seekTo value by multiplying that by the duration and dividing by 100.

Then we set that to the currentTime to change the current time.

Conclusion

We can add an audio player with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Add a Video Player with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a video player with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create video-player

and select all the default options to create the project.

Create the Video Player

We can create the video player by writing:

<template>
  <video width="320" height="240" ref="videoPlayer">
    <source
      src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4"
      type="video/mp4"
    />
    Your browser does not support the video tag.
  </video>
  <div>
    <button @click="play">play</button>
    <button @click="pause">pause</button>
    <button @click="stop">stop</button>
    <button @click="setSpeed(0.5)">0.5x</button>
    <button @click="setSpeed(1)">1x</button>
    <button @click="setSpeed(1.5)">1.5x</button>
    <button @click="setSpeed(2)">2x</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    play() {
      this.$refs.videoPlayer.play();
    },
    pause() {
      this.$refs.videoPlayer.pause();
    },
    stop() {
      const { videoPlayer } = this.$refs;
      videoPlayer.pause();
      videoPlayer.currentTime = 0;
    },
    setSpeed(speed) {
      this.$refs.videoPlayer.playbackRate = speed;
    },
  },
};
</script>

We have the video element with a ref assigned to it.

width and height sets the dimensions of the video.

The source element has the video source.

We set it to the URL to an MP4 clip that we want to play.

Below that, we add buttons to let us play, pause, and stop the video.

We also have buttons that let us change the playback speed.

Then below that, we add some methods that are called when we click on buttons.

The play method lets us play the video by getting the videoPlayer ref with this.$refs.videoPlayer and calling the play method on the returned video element.

The pause method is similar. We get the videoPlayer ref which has the element and call pause on it to pause the video.

A video element has no method to stop a video. But we can implement that by pausing it and resetting the currentTime to 0.

To set the speed of the video, we can set the playbackRate property.

0.5 is half the normal speed.

And anything above 1 is faster than normal speed.

Conclusion

We can add a video player easily into our web app with Vue 3 and JavaScript.