How to do basic Animations with HTML5 Canvas Element and JavaScript API

How to do basic Animations with HTML5 Canvas Element and JavaScript API

In this Canvas crash course, you'll learn how to do basic animations with HTML5 Canvas Element and JavaScript API. We will look at the HTML5 Canvas element and JavaScript API to draw shapes, paths and do some basic animation. <canvas> is an HTML element that allows a user to create graphics using JavaScript. To start a canvas project, we will need an HTML file and a Javascript file. Using JavaScript to control <canvas> elements, it's also very easy to make (interactive) animations

Canvas Crash Course

Learn how to do basic Animations with HTML5 Canvas Element and JavaScript API

In this video we will look at the HTML5 Canvas element and JavaScript API to draw shapes, paths and do some basic animation

  • Intro - 0:20
  • Create Context - 2:05
  • Rectangles (fillRect, strokeRect, etc) - 4:03
  • Paths (moveTo, lineTo) - 9:41
  • Arcs / Circles - 16:15
  • Bezier Curves - 26:18
  • Bounce Animation - 28:45
  • Character Animation - 40:25

GitHub: https://codepen.io/bradtraversy/pen/YzPeNxg

Map Custom Marker and Controls | JavaScript, CSS and API

Map Custom Marker and Controls | JavaScript, CSS and API

How we can add a custom marker on google map using JavaScript & CSS? Solution: JavaScript Google Map Marker With CSS, Custom API Map Controls.

Maybe you have seen custom markers on the map on some tour & travels websites. They show their all destination using those markers on the map. There are many online websites or services for creating custom markers, but we can also create those own using google map’s API. Google provides many kinds of API for developers on its Cloud Platform.

Today you will learn to add a custom marker on the map with your choosing place. This possible because of API, I am using jQuery & jQuery-Migrate for this program. As you know jQuery is a JavaScript library that’s why I am calling this a JavaScript Custom Map Marker Program. Suppose you have an online hotel booking site & you want to show all the places where your hotel is, then this will very useful for you.

So, Today I am sharing JavaScript Google Map Marker With CSSA Custom API Map Controls With JS & CSS. This program marker will place on given longitude & latitude. Its also has zoom in, zoom out, center, & full-screen buttons. There also is an option bar to choosing road view or satellite view. If you want to change the marker to other places, then you have just change the longitude & latitude.

If you are thinking now how this custom map marker actually is, then see the preview given below.

Preview Of Custom API Map Control

See this video preview to getting an idea of how this custom map with marker looks like.


Now you can see this visually. If you like this then get the source code of its.

Discussion

Before sharing source code, let’s talk about this. As you know I have used API, that runs the whole map’s function. I have used an image for the marker’s icon, after that placed on the chosen address in map. For placing the marker I have created some variables for the functions like whole map, long, lat, icon, etc.

All the functions like zoom, focus center, choosing satellite or road view are done by google’s provided API commands. There is another function is when you will click on the marker then the address will open in a new tab. You can remove this feature by removing the code in JS file, I have left a comment on every function’s code section. You can easily identify the codes are for your decided part.

In the CSS section, I have placed all the things you can see on the preview. Works like managing colors, positioning, etc are handled by CSS. As you can see all the buttons in the map are created using Font-Awesome icons. If you have good knowledge of HTML, CSS & JavaScript then you can understand the codes easily. These codes are looking tough but believe me that all are default functions of the API, I have just called on the right place.

For using it on your websites or project you just have to change the longitude & latitude on the JS file. If you get any trouble you can ask me on the comment section or direct message on the Facebook page.

JavaScript Google Map Marker With CSS Source Code

For creating this program you have create 3 files. First for HTML, second for CSS, & third for JavaScript. Follow the steps to creating this without any error.

index.html

Create an HTML file named ‘index.html‘ and put these codes given below.

<!DOCTYPE html>
<!-- code by webdevtrick ( https://webdevtrick.com )-->
<html lang="en" >
 
<head>
  <meta charset="UTF-8">
  <title>CSS Custom Marker On Map | Webdevtrick.com</title>
  
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'>
      <link rel="stylesheet" href="style.css">
</head>
 
<body>
 
  <div class="full-screen">
  <div id="map" class="map"></div>
 
    <!--controls-->
    <span id="zoomIn" class="btn zoom in">
        <i class="fa fa-plus"></i>
    </span>
    <span id="zoomOut" class="btn zoom out">
        <i class="fa fa-minus"></i>
    </span>
 
    <span id="center" class="btn zoom center">
        <i class="fa fa-crosshairs"></i>
    </span>
 
    <div class="mapTypeId">
        <select id="mapTypeId">
            <option value="1">Roadmap</option>
            <option value="2">Satellite</option>
        </select>
    </div>
 
</div>
  <script src='https://maps.googleapis.com/maps/api/js?key=AIzaSyCLFomDOPKqvvITt7tv_hZG0PDlWB2-q0g'></script>
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script>
<script src='https://code.jquery.com/jquery-migrate-1.2.1.min.js'></script>
 
    <script  src="function.js"></script>
 
</body>
</html>

style.css

Now create a CSS file named ‘style.css‘ and put these codes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

/** code by webdevtrick ( https://webdevtrick.com ) **/
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}
.full-screen {
  position: relative;
  width: 100%;
  height: 100%;
}
.full-screen .map {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
.full-screen .btn {
  cursor: pointer;
  border: 0;
  border-radius: 2px;
  background-color: white;
  box-shadow: 1px 1px 3px 0 rgba(0, 0, 0, 0.1);
  transition: all 300ms ease-in-out;
}
.full-screen .btn.zoom {
  position: absolute;
  right: 20px;
  color: #e60023;
  font-size: 20px;
  padding: 5px 8px;
}
.full-screen .btn.zoom.in {
  top: 50%;
  margin-top: -37px;
}
.full-screen .btn.zoom.out {
  bottom: 50%;
  margin-bottom: -37px;
}
.full-screen .btn.zoom.center {
  top: 50%;
  margin-top: -87px;
}
.full-screen .btn.zoom:hover,
.full-screen .btn.zoom:active {
  color: white;
  background-color: #e60023;
}
.full-screen .btn.zoom:active {
  opacity: 0.75;
}
.full-screen .mapTypeId {
  position: absolute;
  top: 20px;
  left: 5px;
  border-radius: 2px;
  background-color: #e60023;
  box-shadow: 1px 1px 3px 0 rgba(0, 0, 0, 0.1);
  width: 90px;
  overflow: hidden;
  color: white;
  padding: 8px 0;
}
.full-screen .mapTypeId select {
  color: white;
  text-indent: 10px;
  text-transform: uppercase;
  font-weight: 700;
  width: 100%;
  position: relative;
  top: -2px;
  border: none;
  box-shadow: none;
  background-color: #e60023;
  background-image: none;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}
.full-screen .mapTypeId select:focus {
  outline: none;
}

function.js

The final step, Create a JavaScript file named ‘function.js‘ and put the codes.

/**code by webdevtrick ( https://webdevtrick.com ) **/
$(document).ready(function() {

var map;
var marker;
var lat = 28.7407056;
var lng = 77.0577493;
var ico = new google.maps.MarkerImage("https://webdevtrick.com/wp-content/uploads/location.png");

var overlay = new google.maps.OverlayView();
overlay.draw = function() {};	

function initialize () {
	var mapCanvas = document.getElementById('map');
	var mapOptions = {
	zoom: 13,
	center: {
	lat: lat, 

     lng: lng
},
mapTypeControl: false,
zoomControl: false,
panControl: false,
        scaleControl: false,
        streetViewControl: false,
        scrollwheel: false
}
 
map = new google.maps.Map( mapCanvas, mapOptions );
 
overlay.setMap(map);
   ZoomControl(map);
   addMarker(map);
  
}
 
// Marker
function addMarker ( map ) {
marker = new google.maps.Marker({
            map: map,
            draggable: false,
            icon: ico,
            position: new google.maps.LatLng( lat, lng )
        });
 
        mouseOverHandler = function () {
         showMarker(marker);
        }
        mouseClickHandler = function () {
         clickMarker(lat, lng);
        }
 
        google.maps.event.addListener( marker, 'click', mouseClickHandler );
        google.maps.event.addListener( marker, 'mouseover', mouseOverHandler );
}
 
// Marker Click
function clickMarker ( lat, lng ) {
var url = 'https://maps.google.com/maps?q='+lat+','+lng+'&z=18';
window.open(url, '_blank');
}
 
// Zoom
function ZoomControl ( map ) {
var zoomIn = document.getElementById('zoomIn');
var zoomOut = document.getElementById('zoomOut');
 
google.maps.event.addDomListener(zoomOut, 'click', function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 0){
map.setZoom(currentZoomLevel - 1);}    
});
 
google.maps.event.addDomListener(zoomIn, 'click', function() {
var currentZoomLevel = map.getZoom();
if(currentZoomLevel != 21){
map.setZoom(currentZoomLevel + 1);}
});
}
 
// MapTypeId
function TypeIdChange ( option ) {
switch (option) {
            case "1":
                map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
                break;
               case "2":
               map.setMapTypeId( google.maps.MapTypeId.SATELLITE );
                break;
            default:
                map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
        }
}
// center
$( '#center' ).on( 'click', function () {
map.setZoom( 13 );
map.setCenter(new google.maps.LatLng( lat, lng ) );
map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
$( '#mapTypeId' ).val( "1" ).trigger('click');
});
 
// center
$( '#center' ).on( 'click', function () {
map.setZoom( 13 );
map.setCenter(new google.maps.LatLng( lat, lng ) );
map.setMapTypeId( google.maps.MapTypeId.ROADMAP );
$( '#mapTypeId' ).val( "1" ).trigger('click');
});
 
$( '#mapTypeId' ).change( function () {
var self = $(this);
TypeIdChange( self.val() );
});
 
google.maps.event.addDomListener( window, 'load', initialize );

That’s It. Now you have successfully created JavaScript Google Map Marker With CSS. In other words, A Custom API Based Map Controls Like add Marker, Zoom In & Out, etc.

Thanks For Visiting, Keep Visiting.

Originally published on https://webdevtrick.com

Learn HTML5 Canvas - DRAW - HTML & JavaScript

Learn HTML5 Canvas - DRAW - HTML & JavaScript

We go over the basics of the HTML5 Canvas element and use JavaScript to draw lines, circles, squares and rectangles to the DOMs Canvas. JavaScript combined with HTML5 Canvas can be used to draw elements anywhere you want inside of the HTML5 Canvas. We learn the basics in a simple how to video but in the next part we will look how to animate the HTML5 Canvas using JavaScript to change the X & Y coordinates of shapes we create. We will follow an Object Oriented Programming pattern.

Building a Simple URL Shortener With HTML and Javascript

Building a Simple URL Shortener With HTML and Javascript

In this article, you''l learn how to build a simple URL shortener with HTML and Javascript

In this article, you''l learn how to build a simple URL shortener with HTML and Javascript

URL Shortener, you might have used one of them in your life such as bit.lygoo.gl and much more. They are useful for shortening long URLs so that you can easily share them with your friends, family or co-workers.

You might be wondering how these things work? To understand how these things work, we need to take a closer look at an url shortener so we’ll be building a simple url shortener. With That Task, we’ll be learning some new things as well as understand how URL Shortener works.

Today, we'll be building a simple url shortener which does not need a database system to host yourself, instead, we'll use jsonstore.io, I'll be assuming that you already know some basic HTML & Javascript.

So without further talking, Let's Start Building. . .

Start with HTML Part :

we'll need only a text input box, a button, and a script tag to create our url shortener.

first create an HTML file called index.html, as there is only a need of two elements, a text input box, a button.

So Let's start adding our three main elements,

<html>
    <body>
        <input type="url" id="urlinput">
        <button onclick="shorturl()">Short The URL</button>
        <script src="main.js"></script>
    </body>
</html>

As I shown in the above code, I've created a simple HTML file. Inside body tags, there're only three elements an input, a button and a script.

the first element is input where we well type/paste our long url, I gave it an id name urlinput so it would be easy to access it inside javascript.

Next element is a button, when we click this button our long url will be shortened as it has onclickfunction which will be executed when we click the button, inside the shorturl() function there will be commands necessary to shorten the url.

At the end we have a script called main.js where all our main javascript codes will be in, above mentioned shorturl() function will be also there.

So, for now, our HTML part is complete. so let's start writing some javascript

Start writing some Javascript :

As we shown above, we'll need some javascript to create our url shortener.

Step 0: as I mentioned at first we'll be using jsonstore.io to store information about our long url, we will need a jsonstore.io endpoint url to store data, Visit jsonstore.io, you'll see something like below

Under the text This Is Your Endpoint you can see a text box with long url such as,

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1

click the purple COPY button.

So Now, let's start writing some javascript . . .

create a javascript file called main.js and start following below steps

first, we must keep the copied link a variable

var endpoint = "https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1";

then we need to generate some random string so that we can create a link between the short url and the long url.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
So, now well create a function called getrandom()

function getrandom(){
    var random_string = Math.random().toString(32).substring(2, 5) + Math.random().toString(32).substring(2, 5);
    return random_string()
}

Don't worry, I'll help you understand the above code,

first, we initiated a function called getrandom than we initialized a variable called random_string and gave it a value.

Math is a built-in javascript object which allows us to perform mathematical tasks on numbers. first we called the random function from Math , Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
Then we transform the returned number to a string using toString() and we gave it an argument of 32 so that we get a proper string not a binary, hexadecimal or octal,

Then we use substring(2,5) as well to slice the string and maintain the size of the string, then again we follow the same procedure to get another chunk of a random string and finally we add both chunks of the string using +

and don't forget to add a return statement returning our random string.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com

function getrandom() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 5; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}


Now Return to index.html and add JQuery because it will be easy to achieve our goals with ease if we use JQuery.

add at the end of body tag but before the main.js script tag

now again return to main.js

let's Create a Function called geturl which will take the value from the input box verify it and return the value

function geturl(){
    var url = document.getElementById("urlinput").value;
    var protocol_ok = url.startsWith("http://") || url.startsWith("https://") || url.startsWith("ftp://");
    if(!protocol_ok){
        newurl = "http://"+url;
        return newurl;
        }else{
            return url;
        }
}

in geturl function we first store the value of the input box in url variable. Then we check if url protocols are ok or not and if the protocol doesn't start with http:// , https:// or ftp:// we add http:// at the beginning of the url then return the url.

Now we will need another function to change the hash in the location bar, let's create

function genhash(){
    if (window.location.hash == ""){
        window.location.hash = getrandom();
    }
}

At first, we check if the hash location is empty if it's empty we than add a random hash to the location bar.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
Next, we'll work on our main function shorturl() , so let's go...

function shorturl(){
    var longurl = geturl();
    genhash();
    send_request(longurl);
}

At first we store the long url in longurl variable then we add a random hash to the location bar so that we can use the url as the short url , then we call the send_request() with an argument longurl , in this function we send JSON request to jsonstore to store the long url with a link to short url , so now let's create the send_request() function.

function send_request(url) {
    this.url = url;
    $.ajax({
        'url': endpoint + "/" + window.location.hash.substr(1),
        'type': 'POST',
        'data': JSON.stringify(this.url),
        'dataType': 'json',
        'contentType': 'application/json; charset=utf-8'
})
}

Here we use JQuery to send JSON request, we send the request to endpoint+"/" + our random string hash from the location bar

as an example,

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

so whenever we will send a get request to the above-mentioned url we'll get the long url as data

Important : add the send_request() function before the shorturl() function , otherwise it will not work

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com> Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
now we will the code to GET the long url linked to the short url entered in the address bar

var hashh = window.location.hash.substr(1)

if (window.location.hash != "") {
    $.getJSON(endpoint + "/" + hashh, function (data) {
        data = data["result"];

        if (data != null) {
            window.location.href = data;
        }

    });


then the above-mentioned code will be executed whenever we put the short url in the address bar (eg. https://shorturl.com/#abcd )

at first, we store the hash value from the url to the hashh variable.

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
then we check if the hash location is empty or not, if not empty we send a get request to the address, endpoint + hashh
Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com

https://www.jsonstore.io/8ba4fd855086288421f770482e372ccb5a05d906269a34da5884f39eed0418a1/abcd

and as usual, if everything is okay we will get the long url from the data which is a JSON array data, from that we extract the result with data["result"].

Assume, we have a random url abcd, our simple url shortener is hosted on https://shortner.com and we have shortened the url https://google.com with that random url, so whenever we go to https://shortner.com/#abcd we will be redirected to https://google.com
Our URL Shortener is Almost Complete! Copy-Paste a long url in the input box then click Short The URL button! Copy The Link from Address Bar, it's your short url!

Some Useful Tricks

We can add a function to automatically copy the short url when a user clicked the Short The URL button Using libraries like SimpleCopy, or ClipboardJS to copy the short url which is currently in the location bar.

if using SimpleCopy We can add simplecopy(window.location.href); at the end of shorturl() function copy the short url whenever use shortens a url

This Simple Url shortener relies on third-party libs such as jsonstore so it would not be a good idea to shorten some confidential long url with it.

You can host the Whole Project in Github/Gitlab pages and set up a simple CNAME, that's it your brand new personal url shortener is ready, you can use any static site hosting service to host your url shortener.