Tag Archives: html5

Angular 2 Tutorial – movies App

Last time I wrote a blog created the MovieAPI and now I am using that API as back end services to create an angular 2 app.

the final source code could find at my github repository.  here is the link download

For the MovieAPI open it, build it will install the packages automatically, then run the service first.

After the service is done, go to the angular2 folder, open command window

–run npm install,

— npm start

It will look like this:

home

create.PNG

added

Step 1 : Setting up your angular 2 application, I already have a blog  click here to found it. Or also could download from the source file from https://github.com/angular/quickstart/blob/master/README.md but it add a lot of unnecessary setting, probably confuse for beginning learner.

It was better do few times manually setting it up to get understand all of the necessary for start anguar 2 application.

Step 2:  In angualr 2 everything is component, for me normally like to create the service first. I just create a file named movies.service.ts under folder movies


import {Injectable} from 'angular2/core';
import {IMovie} from './movie';
import {Http, RequestOptions , Response, Headers} from 'angular2/http';
import {Observable} from 'rxjs/Observable';

@Injectable() 
export class MovieService {   
    private _movieUrl = 'http://localhost:53871/api/movies';

    constructor(private _http: Http) { }

    getMovies(): Observable<IMovie[]> {
        return this._http.get(this._movieUrl)
            .map((response: Response) => <IMovie[]>response.json()) //arrow function, tranceform response to json object and is array of IMovie[]
            .do(data => console.log("All: " + JSON.stringify(data))) //for debug
            .catch(this.handleError);
    }


    createMovie(movie: IMovie): Observable {
        let body = JSON.stringify(movie); 
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this._http.post(this._movieUrl, body, options)               
                .map(this.extractData)
                .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

In there MovieService I have a IMovie here is my movie.ts I put it in the same folder with MovieService .


//interface won't compile to js file, it just for typescript do type checking
 export interface IMovie { 
    movieId: number;
    title: string;
    genre: string;
    classification: string;
    releaseDate: number;
    rating: number;
    cast: string[];

}


export class Movie implements IMovie {
    movieId: number;
    title: string;
    genre: string;
    classification: string;
    releaseDate: number;
    rating: number;
    cast: string[];
}

Step 3: Inject the services.
Go to the app.component.ts this is our container component, for anguar 2 only need inject once, then all of the nest container could using it ( by import it ).

Inject a service has two steps:

1) import the file into the app.component,

2) Inject it as providers

here is my app.component.ts

angular2_injection

Step 4: Create the movies-list.component.ts


//for using component, simply import it into this file
import {Component, OnInit} from 'angular2/core';
import { ROUTER_DIRECTIVES } from 'angular2/router';

import {IMovie} from './movie';
import {MovieService} from './movies.service';
import {MovieFilterPipe} from './movie-filter.pipe';
import { StarComponent } from '../shared/star.component';

@Component({
    selector: 'sz-movies',
    templateUrl: 'app/movies/movies-list.component.html',
    styleUrls: ['app/movies/movies-list.component.css'],  
    pipes: [MovieFilterPipe],
    directives: [StarComponent, ROUTER_DIRECTIVES]
   
})
export class MovieListComponent implements OnInit {
    pageTitle: string = 'Movie List';   
   
    listFilter: string;
    errorMessage: string;
    movies: IMovie[];


    constructor(private _movieService: MovieService) {

    }
    
    ngOnInit(): void {
        this._movieService.getMovies()
            .subscribe(
            movies => this.movies = movies,
            error => this.errorMessage = error);
    }

}

here is the movies-list.component.htmlmovies_html

 

for this component I have a nested StarComponent.

Setp 5: create nested StarComponent, here is the star.component.ts under the share folder


import { Component, OnInit, Input} from 'angular2/core';
@Component({
    selector: 'sz-star',
    templateUrl: 'app/shared/star.component.html',
    styleUrls: ['app/shared/star.component.css']
})
export class StarComponent implements OnInit {
    @Input() rating: number;
    starWidth: number;
    ngOnInit(): void {
        this.starWidth = this.rating * 86 / 5;
    }
}

star.component.htmlstar.PNG

css:

star_css

In angular 2: data flow is unidirectional, for passing data from view to the class

first: you passing data into the directive could bind it to the property

passing_data_down.PNG

Second: need import the Input from angular2/core, and bind it to the property

inData

Now, one nested movies-list.component and nested star.componet down.

Now using the same steps create the MovieCreateComponent


import {Component, OnInit} from 'angular2/core';

import {IMovie, Movie} from '../movie';
import {Router} from 'angular2/router';
import {MovieService} from '../movies.service';

@Component({
    templateUrl: 'app/movies/create/movie-create.component.html'
})

export class MovieCreateComponent implements OnInit {
    title: string = 'Create New Movie';
    newMovie: IMovie;

    constructor(
        private _moviesService: MovieService,
        private _router: Router
    ) { }

    ngOnInit() {
        this.newMovie = new Movie;
    }

    createMovie(event) {
        let _this = this;

        this._moviesService.createMovie(this.newMovie)
            .subscribe(function () {
                _this._router.navigate(['Movies']);
            });
    }

    cancelCreate(event) {
        this._router.navigate(['Movies']);
    }

}angular2_form.PNG
Router:
route.PNG

In the index.html page, put the baseurl:
baseUrl.png

Done, have fun!

Create marquee news in front page and the news is read from the database with expired data,also included management page to insert news

My boss just saw other company website has a marquee new on the front page, so she asked me if I could make one and arrow her to insert news and the news will dispear at the expired data.

For achieve that task, first I create a table in my database table, here is my table:

breadNewTable

then I write a store proceedure, a little tip for fresh guy, alway use store preceedure to insert data for security reasons.

breadNewStoreProceedure

Now, We could start the front end job. I create a user control:marquee.ascx(so you could put it in anyway you like), to display the new, here is my html code:

frontUCmarquee

here is the backcod, I used ado.net to open the database and qurery what I need, and bind it to my BulledtedList:

databasereadertomarquee

See the code this if(!IsPostBack) is not neccessary, but I use web froms so it wil inherit maintain state so I don’t need retrieve database everytime postback.

here I am also happy to share the css file for style this unorder list to display inline:

MarqueeCssStyle

A tip for fresh guy, put this in the page your use control will stand it.

Now, you just need drag the usercontrol to any page you want it with this css style in top of the header it. You coud see it.

Then We could start create a page to arrow my boss to insert the bread news, I used boostrap format so it save my time to write css. here is the front page look like:

addNews

here is the html code:

htmlCodeAddnews

The form use jQury Validate, the jquery-ui.js, is for my boss click then will pop up the jQuery calender to arrow her to put the expired date. So simple isn’t, I am love JQure very much, save a lot of time. It remind me when I first time write javascript over 10 years ago, for every simply function I need write a lot codes.

Finally I just need write a event could be fired by this button.

storeIntodatabase

Ok, That’s all. Have fun!

Bootrap Jumbotron into WordPress Theme

In this post I will use a bootstrap Jumbotron template,here is the link http://getbootstrap.com/examples/jumbotron/  I will  customize it into wordpress theme

You need download bootstrap into” yourtheme “folder, whatever theme name you like to call it.

bootstrap_to_wordpress2

 

Those fold should inside your theme folder, don’t worry what are inside it except everything from bootstrap, the other file is empty now.

1) for wordpress could read you theme you need put those on top of your style.css:

/*
Theme Name: Bootstrap to WordPress
Theme URI: http://sandywebdesigner.com
Author: Sandy Zhang
Author URI: http://sandywebdesigner.com
Description: Example theme for  how to convert static Bootstrap site into dynamic WordPress theme
Version: 1.0
License:
License URI:
Text Domain: bootstrap-to-wp

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you’ve learned with others.
*/

/* Move down content because we have a fixed navbar that is 50px tall */
body {
padding-top: 50px;
padding-bottom: 20px;
}
.admin-bar .navbar-fixed-top {
margin-top: 30px;
}
/* Below is the style for navigation in functions.php add a class to sub-menu to the navigation so I just write a simple style to it,you could customize it by yourself */
@media (min-width:768px) {
.sub-menu {
display: none;
position: absolute;
background: #222;
padding: 10px 15px;
width: 150px;
}

li:hover .sub-menu {
display: block;
}

}

.sub-menu li {
margin-bottom: 10px;
list-style: none;
}

.sub-menu li:last-child {
margin-bottom: 0;
}

.sub-menu a  {
color: #999;
text-decoration: none;
}

.sub-menu a:hover  {
color: #fff;
}

.current-menu-item > a, .current-menu-parent > a {
background: #000;
}
.current-menu-parent li a {
background: inherit;
}
.current-menu-parent .current-menu-item a {
color: #fff;
font-weight: bold;
}

.sidebar{
margin-top:40px;
color:#444;
}
.sidebar h3{
color:#888;
}
.widget{
margin:10px 0 30px;
}
article .post{
margin:20px 0;
}

.featured-image img,
.portfolio-piece img,
.portfolio-image img {
max-width:100%;
}

.prev-next{
font-size:24px;
margin-top:30px;
text-align:right;
}

@media (max-width:540px) {
.portfolio-piece h4{
font-size:.8em;
}
.prev-next{
font-size:15px;
margin-top:15px;
text-align:right;
}

}

2)header.php

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset=”<?php bloginfo( ‘charset’ ); ?>”>
<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”shortcut icon” href=”<?php bloginfo(‘template_directory’);?>/images/favicon.ico”>

<title>
<?php wp_title(‘|’,true,’right’);?>
<?php bloginfo(‘name’)?>

</title>

<?php wp_head(); ?>
</head>

<body <?php body_class(); ?>>

<div class=”navbar navbar-inverse navbar-fixed-top” role=”navigation”>
<div class=”container”>
<div class=”navbar-header”>
<button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”.navbar-collapse”>
<span class=”sr-only”>Toggle navigation</span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
</button>
<a class=”navbar-brand” href=”<?php bloginfo(‘url’); ?>”><?php bloginfo(‘name’); ?></a>
</div>
<div class=”navbar-collapse collapse”>
<?php
$args = array(
‘menu’ => ‘mainmenu’,
‘menu_class’ => ‘nav navbar-nav’,
‘container’ => ‘false’
);
wp_nav_menu($args);
?>
</div><!–/.navbar-collapse –>
</div>
</div>

3)footer.php

<hr>

<footer>
<p>&copy; <?php bloginfo(‘name’);?> <?php echo date(‘Y’); ?></p>
</footer>
</div> <!– /container –>
<?php wp_footer(); ?>
</body>
</html>

3)index.php

<?php get_header(); ?>

<div class=”container”>

<div class=”row”>
<div class=”col-md-9″>
<?php if(have_posts()):while(have_posts()):the_post();?>
<div class=”Page-header”>
<h1><?php the_title(); ?></h1>
</div>
<?php the_content();?>
<?php endwhile; else:?>

<div class=”Page-header”>
<h1>Oh no!</h1>
</div>
<p>No content is appearing for this page!</p>
<?php the_content();?>

<?php endif;?>

</div>
<?php get_sidebar(); ?>

</div>

<?php get_footer(); ?>

4)functions.php

<?php
function theme_styles(){
wp_enqueue_style( ‘bootstrap_css’, get_template_directory_uri() . ‘/css/bootstrap.min.css’ );
wp_enqueue_style( ‘main_css’, get_template_directory_uri() . ‘/style.css’ );
}
add_action( ‘wp_enqueue_scripts’, ‘theme_styles’ );

function theme_js(){
global $wp_scripts;
wp_register_script( ‘html5_shiv’, ‘https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js&#8217;, ”, ”, false );

wp_register_script( ‘respond_js’, ‘https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js&#8217;, ”, ”, false );

$wp_scripts->add_data( ‘html5_shiv’, ‘conditional’, ‘lt IE 9’ );
$wp_scripts->add_data( ‘respond_js’, ‘conditional’, ‘lt IE 9’ );
wp_enqueue_script( ‘bootstrap_js’, get_template_directory_uri() . ‘/js/bootstrap.min.js’, array(‘jquery’), ”, true );
wp_enqueue_script( ‘theme_js’, get_template_directory_uri() . ‘/js/theme.js’, array(‘jquery’,’bootstrap_js’), ”, true );

}

add_action( ‘wp_enqueue_scripts’, ‘theme_js’ );

add_theme_support(‘menus’);
add_theme_support(‘post-thumbnails’);

function register_theme_menus() {
register_nav_menus(
array(
‘header-menu’    => __( ‘mainmenu’ )
)
);
}
add_action( ‘init’, ‘register_theme_menus’ );

function create_widget( $name, $id, $description ) {

register_sidebar(array(
‘name’ => __( $name ),
‘id’ => $id,
‘description’ => __( $description ),
‘before_widget’ => ‘<div class=”widget”>’,
‘after_widget’ => ‘</div>’,
‘before_title’ => ‘<h2>’,
‘after_title’ => ‘</h2>’
));
}

create_widget( ‘Front Page Left’, ‘front-left’, ‘Displays on the left of the homepage’ );
create_widget( ‘Front Page Center’, ‘front-center’, ‘Displays in the center of the homepage’ );
create_widget( ‘Front Page Right’, ‘front-right’, ‘Displays on the right of the homepage’ );
?>

See how simple it is, index.php you completed, then use this index.php to create other template like page.php. single.php, etc. Have fun!

 

 

 

 

 

 

Set up your backbone

Set up your backbone is really ease, just down the backbone, and underscore into your local file, and the jQuery just use the google jQuery, so you just add this the link to your web page, it will fast your website(this is called CDNS: content delivery networks,common quesion for fornt-end designer interviews).

so your page’s code just like this:

<!DOCTYPE HTML>
<html>
<head>
<title>Backbone Tutorials</title>
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js”></script&gt;
<script src=”underscore.js” type=”text/javascript”></script>
<script src=”backbone.js” type=”text/javascript”></script>
</head>
<body>
<script type=”text/javascript”>

</script>

</body>

</html>

How You Can Draw Regular Polygons with the HTML5 Canvas API

How it is look likes goes to here:

http://www.sandywebdesigner.com/canvas/canvas.html

  • a circle is 2 * Pi
  • don’t know how to explain sine and cosine, but if you understand below is help you under stand my JavaScript code.
  • x = r * cosine(a)
    y = r * sine(a)

And here is the JavaScript code for you Polygons

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) {
if (sides < 3) return;
var a = (Math.PI * 2)/sides;
a = anticlockwise?-a:a;
ctx.save();
ctx.translate(x,y);
ctx.rotate(startAngle);
ctx.moveTo(radius,0);
for (var i = 1; i < sides; i++) {
ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i));
}
ctx.closePath();
ctx.restore();
}

When I need a pentagon,here is the code for get it.

function doFirst(){
var x = document.getElementById(“canvas”);

context= x.getContext(‘2d’);

context.beginPath();
polygon(context, 120,120,100,5);
context.stroke();
}
window.addEventListener(“load”,doFirst,false);

And You could use below code generate different shapes.

function doFirst(){
var x = document.getElementById(“canvas”);

context= x.getContext(‘2d’);

context.beginPath();
polygon(context,125,125,100,5,-Math.PI/2);
context.fillStyle=”rgba(227,11,93,0.75)”;
context.fill();
context.stroke();

// Draw a circle to encompass this polygon
context.beginPath();
context.arc(125, 125, 100, 0, Math.PI * 2);
context.stroke();

context.beginPath();
polygon(context,350,125,100,6,-Math.PI/2);
context.fillStyle=”rgba(51,128,255,0.75)”;
context.fill();
context.stroke();

context.beginPath();
polygon(context,125,350,100,7,-Math.PI/2);
context.fillStyle=”rgba(11,227,93,0.75)”;
context.fill();
context.stroke();

context.beginPath();
polygon(context,350,350,100,8,0,false);
polygon(context,350,350,60,8,0,true);
context.fillStyle=”rgba(227,11,93,0.75)”;
context.shadowColor = ‘rgba(0,0,0,0.75)’;
context.shadowOffsetX = 8;
context.shadowOffsetY = 8;
context.shadowBlur = 10;
context.fill();
}
window.addEventListener(“load”,doFirst,false);

Create a video in your HTML5 page, here is the javascript code you needed it

Here i put the java script source code make your video work.

here the final file you needed it.

function doFirst(){
    barSize=600;
    myMovie=document.getElementById(‘myMovie’);
    playButton=document.getElementById(‘playButton’);
    bar=document.getElementById(‘defaultBar’);
    progressBar=document.getElementById(‘progressBar’);
    
    playButton.addEventListener(‘click’,playOrPause,false);
    bar.addEventListener(‘click’,clickedBar,false);
}
function playOrPause(){
   if(!myMovie.paused && !myMovie.ended ) {
       myMovie.pause();
       playButton.innerHTML=’Play’;
       window.clearInterval(updateBar);
   }else{
       myMovie.play();
       playButton.innerHTML=’Pause’;
       updateBar=setInterval(update,500);
   }
}

function update(){
    if(!myMovie.ended){
        var size=parseInt(myMovie.currentTime*barSize/myMovie.duration);
        progressBar.style.width=size+’px’;
    }else{
         progressBar.style.width=’0px’;
          playButton.innerHTML=’Play’;
          window.clearInterval(updateBar);
    }
}

function clickedBar(e){
    if(!myMovie.paused && !myMovie.ended){
        var mouseX=e.pageX-bar.offsetLeft;
        var newtime=mouseX*myMovie.duration/barSize;
        myMovie.currentTime=newtime;
        progressBar.style.width=mouseX+’px’;
        
    }
}
window.addEventListener(‘load’,doFirst,false);

Then here is your css code for add video to your html5 page–continue

Here I put the css style for mark up your video appearance. not very beautiful, but it works, you could change this to what you like.

Css3 style below: (next post is the javascript file, you need add to make the video works.)

body{
text-align:center;
}
header,section,footer,aside,nav,article,hgroup{
display:block;
}
#skin{
width:700px;
margin:10px auto;
padding:5px;
background:red;
border:4px solid black;
border-radius: 10px;
}
nav{
margin:5px 0px;
}
#buttons{
float:left;
width:70px;
height:22px;
}
#defaultBar{
position: relative;
float:left;
width:600px;
height: 16px;
padding:4px;
border:2px solid black;
background-color:yellow;
}
#progressBar{
position: absolute;
width:0px;
height:16px;
background:blue;
}

Create a video in your HTML5 page–continue

Here I am going to continue my post. HTML5 page added video is much easy now.

put below source code in your html body ,next post is the css style.

<section id = “skin”>
<video id=”myMovie” width=”640″ height=”360″>
<source src=”videos/movie.mp4″ type=’video/mp4′ >
</video>

<nav>
<div id=”buttons”>
<button type=”button” id=”playButton”>Play</button>
</div>
<div id=”defaultBar”>
<div id=”progressBar”>
</div>
</div>
<div style=”clear: both;”>

</div>

</nav>

</section>