DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Avatar

Andrey Prikaznov

Web developer at Jagonal

Sydney / Chatswood, AU

Joined Apr 2010

https://www.script-tutorials.com/

About

I was born in 1981 in one little city. Since I was 10y/o I programmed in different languages. My first languages were basic, then C++/MFC, after .Net (C#, VB.Net, J#, ASP.Net), XSL+XML processing). In the last 5 years I worked with web languages (HTML, CSS, PHP, SQL, XML, XSL, JavaScript). After university I worked in several different companies, eventually becoming a blogger. This is my hobby too.

Stats

Reputation: 485
Pageviews: 2.4M
Articles: 20
Comments: 6
  • Articles
  • Comments

Articles

article thumbnail
Backend Web API With C#: Step-by-Step Tutorial
Lean how to create a .NET-based backend application in VS that pulls from a Web API using the C# language.
August 27, 2018
· 467,395 Views · 18 Likes
article thumbnail
Top Ten Reasons Web Developers Should Use AngularJS
Angular is a powerful tool that lets you develop highly interactive and intuitive web applications, without any hustle. Hopefully, these 10 reasons will give you an idea why Angular JavaScript is a modern-age web development tool.
May 30, 2016
· 26,307 Views · 4 Likes
article thumbnail
Angular JS Tutorial – MVC and MVVM Design Patterns
In the first part of a series on Angular JS tutorials, the author walks through some design patterns.
February 20, 2016
· 66,170 Views · 9 Likes
article thumbnail
A Look Into HTML6 - What Is It, and What Does it Have to Offer?
HTML is a simple web development language that keeps on rolling out new versions, and has started working on its sixth revision. HTML5 the current revision of HTML is considered to be one of the most sought-after revisions, compared to all the previous HTML versions. Let’s have an Overview of HTML5 HTML5 gave us some very exciting features like audio and video support, offline local storage, and most importantly ability to build mobile optimized websites. In addition, it gave us freedom from using type attribute from tags such as and
December 5, 2014
· 12,057 Views
article thumbnail
Tutorial: How to Create a Responsive Website with AngularJS
in today’s tutorial, i’m going to show you the process of creating nearly an entire website with a new library – angularjs. however, i would like to introduce to you to angularjs first. angularjs is a magnificent framework by google for creating web applications. this framework lets you extend html’s syntax to express your application’s components clearly and succinctly, and lets you use standard html as your main template language. plus, it automatically synchronizes data from your ui with your js objects through 2-way data binding. if you’ve ever worked with jquery, the first thing to understand about angular is that this is a completely different instrument. jquery is a library, but angularjs is framework. when your code works with the library, it decides when to call a particular function or operator. in the case of the framework, you implement event handlers, and the framework decides at what moment it needs to invoke them. using this framework allows us to clearly distinguish between templates (dom), models, and functionality (in controllers). let’s come back to our template, take a look at our result: live demo download in package description this template is perfect for business sites. it consists of several static pages: projects, privacy, and about pages. each product has its own page. there is also a contact form for communication. that is all that is necessary for any small website. moreover, it is also a responsive template, thus it looks good on any device. i hope you liked the demo, so if you’re ready – let’s start making this application. please prepare a new folder for our project, and then create new folders in this directory: css – for stylesheet files images – for image files js – for javascript files (libraries, models, and controllers) pages – for internal pages stage 1. html the main layout consists of four main sections: a header with navigation, a hidden ‘contact us’ form, a main content section, and a footer. first we have to prepare a proper header: index.html as you can see, it’s an ordinary header. now – the header with the navigation: our projects privacy & terms about contact us it's an ordinary logo, and the menu is the usual ul-li menu. the next section is more interesting – the ‘contact us’ form: contact us send message your message has been sent, thank you. finally, the last key element is the main content section: have you noticed the numerous ‘ng-’ directives? all these directives allow us to do various actions directly in the dom, for example: ng-class – the ngclass allows you to set css classes on an html element dynamically by databinding an expression that represents all classes to be added. ng-click – the ngclick allows you to specify custom behavior when element is clicked. ng-hide – the nghide directive shows and hides the given html element conditionally based on the expression provided to the nghide attribute. ng-include – fetches, compiles, and includes an external html fragment. ng-model – is a directive that tells angular to do two-way data binding. ng-show – the ngshow directive shows and hides the given html element conditionally based on the expression provided to the ngshow attribute. ng-submit – enables binding angular expressions to onsubmit events. stage 2. css in this rather large section, you can find all the styles used: css/style.css /* general settings */ html { min-height:100%; overflow-x:hidden; overflow-y:scroll; position:relative; width:100%; } body { background-color:#e6e6e6; color:#fff; font-weight:100; margin:0; min-height:100%; width:100%; } a { text-decoration:none; } a img { border:none; } h1 { font-size:3.5em; font-weight:100; } p { font-size:1.5em; } input,textarea { -webkit-appearance:none; background-color:#f7f7f7; border:none; border-radius:3px; font-size:1em; font-weight:100; } input:focus,textarea:focus { border:none; outline:2px solid #7ed7b9; } .left { float:left; } .right { float:right; } .btn { background-color:#fff; border-radius:24px; color:#595959; display:inline-block; font-size:1.4em; font-weight:400; margin:30px 0; padding:10px 30px; text-decoration:none; } .btn:hover { opacity:0.8; } .wrap { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; margin:0 auto; max-width:1420px; overflow:hidden; padding:0 50px; position:relative; width:100%; } .wrap:before { content:''; display:inline-block; height:100%; margin-right:-0.25em; vertical-align:middle; } /* header section */ header { height:110px; } header .wrap { height:100%; } header .logo { margin-top:1px; } header nav { float:right; margin-top:17px; } header nav ul { margin:1em 0; padding:0; } header nav ul li { display:block; float:left; margin-right:20px; } header nav ul li a { border-radius:24px; color:#aaa; font-size:1.4em; font-weight:400; padding:10px 27px; text-decoration:none; } header nav ul li a.active { background-color:#c33c3a; color:#fff; } header nav ul li a.active:hover { background-color:#d2413f; color:#fff; } header nav ul li a:hover,header nav ul li a.activesmall { color:#c33c3a; } /* footer section */ footer .copyright { color:#adadad; margin-bottom:50px; margin-top:50px; text-align:center; } /* other objects */ .projectobj { color:#fff; display:block; } .projectobj .name { float:left; font-size:4em; font-weight:100; position:absolute; width:42%; } .projectobj .img { float:right; margin-bottom:5%; margin-top:5%; width:30%; } .paddrow { background-color:#dadada; color:#818181; display:none; padding-bottom:40px; } .paddrow.aboutrow { background-color:#78c2d4; color:#fff !important; display:block; } .paddrow .head { font-size:4em; font-weight:100; margin:40px 0; } .paddrow .close { cursor:pointer; position:absolute; right:50px; top:80px; width:38px; } .about { color:#818181; } .about section { margin:0 0 10%; } .about .head { font-size:4em; font-weight:100; margin:3% 0; } .about .subhead { font-size:2.5em; font-weight:100; margin:0 0 3%; } .about .txt { width:60%; } .about .image { width:26%; } .about .flleft { float:left; } .about .flright { float:right; } .projecthead.product { background-color:#87b822; } .projecthead .picture { margin-bottom:6%; margin-top:6%; } .projecthead .picture.right { margin-right:-3.5%; } .projecthead .text { position:absolute; width:49%; } .projecthead .centertext { margin:0 auto; padding-bottom:24%; padding-top:6%; text-align:center; width:55%; } .image { text-align:center; } .image img { vertical-align:top; width:100%; } .contactform { width:50%; } .input { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; margin:1% 0; padding:12px 14px; width:47%; } .input.email { float:right; } button { border:none; cursor:pointer; } .textarea { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; height:200px; margin:1% 0; overflow:auto; padding:12px 14px; resize:none; width:100%; } ::-webkit-input-placeholder { color:#a7a7a7; } :-moz-placeholder { color:#a7a7a7; } ::-moz-placeholder { /* ff18+ */ color:#a7a7a7; } :-ms-input-placeholder { color:#a7a7a7; } .loader { -moz-animation:loader_rot 1.3s linear infinite; -o-animation:loader_rot 1.3s linear infinite; -webkit-animation:loader_rot 1.3s linear infinite; animation:loader_rot 1.3s linear infinite; height:80px; width:80px; } @-moz-keyframes loader_rot { from { -moz-transform:rotate(0deg); } to { -moz-transform:rotate(360deg); } } @-webkit-keyframes loader_rot { from { -webkit-transform:rotate(0deg); } to { -webkit-transform:rotate(360deg); } } @keyframes loader_rot { from { transform:rotate(0deg); } to { transform:rotate(360deg); } } .view-enter,.view-leave { -moz-transition:all .5s; -o-transition:all .5s; -webkit-transition:all .5s; transition:all .5s; } .view-enter { left:20px; opacity:0; position:absolute; top:0; } .view-enter.view-enter-active { left:0; opacity:1; } .view-leave { left:0; opacity:1; position:absolute; top:0; } .view-leave.view-leave-active { left:-20px; opacity:0; } please note that css3 transitions are used, which means that our demonstration will only work modern browsers (ff, chrome, ie10+ etc) stage 3. javascript as i mentioned before, our main controller and the model are separated. the navigation menu can be handled here, and we also can operate with the contact form. js/app.js 'use strict'; // angular.js main app initialization var app = angular.module('example359', []). config(['$routeprovider', function ($routeprovider) { $routeprovider. when('/', { templateurl: 'pages/index.html', activetab: 'projects', controller: homectrl }). when('/project/:projectid', { templateurl: function (params) { return 'pages/' + params.projectid + '.html'; }, controller: projectctrl, activetab: 'projects' }). when('/privacy', { templateurl: 'pages/privacy.html', controller: privacyctrl, activetab: 'privacy' }). when('/about', { templateurl: 'pages/about.html', controller: aboutctrl, activetab: 'about' }). otherwise({ redirectto: '/' }); }]).run(['$rootscope', '$http', '$browser', '$timeout', "$route", function ($scope, $http, $browser, $timeout, $route) { $scope.$on("$routechangesuccess", function (scope, next, current) { $scope.part = $route.current.activetab; }); // onclick event handlers $scope.showform = function () { $('.contactrow').slidetoggle(); }; $scope.closeform = function () { $('.contactrow').slideup(); }; // save the 'contact us' form $scope.save = function () { $scope.loaded = true; $scope.process = true; $http.post('sendemail.php', $scope.message).success(function () { $scope.success = true; $scope.process = false; }); }; }]); app.config(['$locationprovider', function($location) { $location.hashprefix('!'); }]); pay attention here. when we request a page, it loads an appropriate page from the ‘pages’ folder: about.html, privacy.html, index.html. depending on the selected product, it opens one of the product pages: product1.html, product2.html, product3.html or product4.html in the second half, there are functions to slide the contact form and to handle its submit process (to the sendemail.php page). next is the controller file: js/controllers.js 'use strict'; // optional controllers function homectrl($scope, $http) { } function projectctrl($scope, $http) { } function privacyctrl($scope, $http, $timeout) { } function aboutctrl($scope, $http, $timeout) { } it is empty, because we have nothing to use here at the moment. stage 4. additional pages angularjs loads pages asynchronously, thereby increasing the speed. here are templates of all additional pages used in our project: pages/about.html about us script tutorials is one of the largest web development communities. we provide high quality content (articles and tutorials) which covers all the web development technologies including html5, css3, javascript (and jquery), php and so on. our audience are web designers and web developers who work with web technologies. additional information promo 1 lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. ..... pages/privacy.html privacy & terms by accessing this web site, you are agreeing to be bound by these web site terms and conditions of use, all applicable laws and regulations, and agree that you are responsible for compliance with any applicable local laws. if you do not agree with any of these terms, you are prohibited from using or accessing this site. the materials contained in this web site are protected by applicable copyright and trade mark law. other information header 1 lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. ..... pages/footer.html copyright © 2013 script tutorials pages/index.html product #1 product #2 product #3 product #4 finally, the product pages. all of them are prototypes, so i decided to publish only one of them. pages/index.html product 1 page lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. download the app finishing touches – responsive styles all of these styles are needed to make our results look equally good on all possible mobile devices and monitors: @media (max-width: 1200px) { body { font-size:90%; } h1 { font-size:4.3em; } p { font-size:1.3em; } header { height:80px; } header .logo { margin-top:12px; width:200px; } header nav { margin-top:11px; } header nav ul li { margin-right:12px; } header nav ul li a { border-radius:23px; font-size: 1.3em; padding:10px 12px; } .wrap { padding:0 30px; } .paddrow .close { right:30px; } } @media (max-width: 900px) { .contactform { width:100%; } } @media (max-width: 768px) { body { font-size:80%; margin:0; } h1 { font-size:4em; } header { height:70px; } header .logo { margin-top:20px; width:70px; } header nav { margin-top:8px; } header nav ul li { margin-right:5px; } header nav ul li a { border-radius:20px; font-size:1.1em; padding:8px; } .wrap { padding:0 15px; } .projectobj .name { font-size:3em; } .paddrow { padding-bottom:30px; } .paddrow .head { font-size:3em; margin:30px 0; } .paddrow .close { right:20px; top:60px; width:30px; } .projecthead .picture { width:67%; } .projecthead .picture.right { margin-right:16.5%; } .projecthead .text { position:static; width:100%; } .projecthead .centertext { width:70%; } .view-enter,.view-leave { -webkit-transform:translate3d(0,0,0); transform:translate3d(0,0,0); } } @media (max-width: 480px) { body { font-size:70%; margin:0; } header { height:50px; } header .logo { display:none; } header nav { margin-top:3px; } header nav ul li { margin-right:3px; } header nav ul li a { border-radius:20px; font-size:1.3em; padding:5px 14px; } #contactbtn { display:none; } .wrap { padding:0 10px; } .paddrow { padding-bottom:20px; } .paddrow .head { margin:20px 0; } .paddrow .close { right:10px; top:45px; width:20px; } .about .image { margin:10% auto; width:60%; } .about .abicon { display:inline; } .projecthead .centertext { width:90%; } .about .txt,.input { width:100%; } .about .flleft,.about .flright,.input.email { float:none; } } live demo download in package conclusion that’s all for today. thanks for your patient attention, and if you really like what we did today, share it with all your friends in your social networks.
October 10, 2013
· 312,268 Views · 10 Likes
article thumbnail
Recreating "Snake" using HTML5 Canvas and KineticJS
in the beginning, before you start making a new game, you need to prepare the concept (logic) of the game. you need to have a clear idea about it. you need to develop a high level of understanding, without going into the fine details. in the first phase, we find the answer "what" we want to create, and we reserve the answers to "how to do" for the upcoming stages. let me illustrate this method with an example. let’s develop the popular game "snake". this game was popular long ago, even on consoles and old cell phones with text user interfaces. concept of the game initially a small sized snake appears on the screen which keeps running for the rest of the game like endless runner. player can change the direction only. speed of the snake increases with time. length of the snake also increases after eating randomly appearing food. increasing length and speed of the snake adds difficulty to the game over time. we can use storyboard technique to graphically represent our idea. according to wikipedia: "storyboards are graphic organizers in the form of illustrations or images displayed in sequence for the purpose of pre-visualizing a motion picture, animation, motion graphic or interactive media sequence." here is our storyboard: for your convenience i am adding the description of each storyboard screen: screen 1: snake (square) waiting for a key-press to start moving. circle is shown as food item. screen 2: after eating (hitting) food item the snake’s length increases and food item appears at another random location. screen 3: snake can re-enter the playing area from the opposite edge after leaving it from an edge. screen 4: snake dies after biting itself here, uml statechart diagram may also help to understand different "states" of the snake during a game. according to wikipedia: "a state diagram is a type of diagram used in computer science and related fields to describe the behavior of systems. state diagrams require that the system described is composed of a finite number of states; sometimes, this is indeed the case, while at other times this is a reasonable abstraction. many forms of state diagrams exist, which differ slightly and have different semantics." here is our statechart diagram: in the diagram, edges represent the actions and the ovals represent the states a snake is in after the specific action. game starts with an idle snake. you can move snake in all four directions using arrow keys. while moving in any direction when a key is pressed, the snake goes to "deciding" state to determine which key was pressed and then again goes to the respective direction. snake eats food when encountered while moving. there is also a "dead" state if snake hits itself while moving. you may also want to add more state diagrams for prominent objects to clarify. there are other uml diagrams which may help you describe your game project. these diagrams are not only helpful for yourself but also helps if you are working in a team making team communication easy and unambiguous. structure of the game the play area in virtually divided into a 200?200-pixel grid having 10?10-pixel cells. the initgrid() function prepares the grid. as you can guess from the code that the snake’s width and height is also 10?10 pixels. so as a programming trick, i used the height and width of the snake to represent the dimensions of a single cell. function initgrid() { //*****initialize grid ... cell = {"col":col*snakeheight, "row":row*snakewidth}; ... } you are right if you are thinking about the usage of this virtual grid. in fact, during the initialization of the game structure, this grid helps us to identify the places (cells…to be precise) where we can put the snake and food randomly. a random number generator function randomcell(cells) gives us a random number which we use as an index to the grid array and get the coordinates stored against that specific index. here is the random number generator function… function randomcell(cells) { return math.floor((math.random()*cells)); } math.random and math.floor are both javascript functions. the following code shows the usage of grid and random number generator function… var initsnakeposition = randomcell(grid.length - 1); //pass number of cells var snakepart = new kinetic.rect({ name: 'snake', x: grid[initsnakeposition].col, y: grid[initsnakeposition].row, width: snakewidth, height: snakeheight, fill: 'black', }); kinetic.rect constructor constructs the initial single rectangle to represent the snake. later, when the snake would grow after eating the food, we would be adding more rectangles. each rectangle is assigned a number to represent its actual position in the snake array. as there is only one rectangle at the moment, we assign it position 1. snakepart.position = snakeparts; snakeparts is a counter which keeps counting the number of parts in the snake array. you might be wondering that we have not created any array of snakepart objects but we are talking about array? in fact if you keep the value of name: property same for all the snakepart objects, kineticjs would return all those objects as an array if you ask like this… var snakepartsarray = stage.get('.snake'); you will see the usage of this feature in action later in the code. snakepart.position shows how you can add custom properties to kinetic.rect object dynamically, or to any other object. why we need the position when kineticjs can return indexed array? please don’t bother yourself with this question at the moment, you will find the answer if you keep reading. two more identifications are required to make the job more easy to manage the snake actions and movements, snake head and tail. there is only one snake-part (rectangle) to begin with therefore both head and tail pointers point to the same rectangle. var snaketail; var snakehead; ... snakehead = snakepart; snaketail = snakepart; we are done with setting up the snake. to construct the food which is a simple circle of radius 5 see the following code… var randomfoodcell = randomcell(grid.length - 1); var food = new kinetic.circle({ id: 'food', x:grid[randomfoodcell].col+5, y:grid[randomfoodcell].row+5, radius: 5, fill: 'black' }); kinetic.circle constructs the food for our snake game. here adding +5 to x and y coordinates to place the circle exactly in the centre of a 10?10 cell provided that the radius of the circle is 5. after we are done with the creation of basic shapes for our game and their positions on the game area/grid we need to add those shapes to a kinetic.layer and then add that layer to the kinetic.stage. // add the shapes (sanke and food) to the layer var layer = new kinetic.layer(); layer.add(snakepart); layer.add(food); // add the layer to the stage stage.add(layer); the ‘stage’ object used in the cod above has already been created in the beginning using the following code snippet… //stage var stagewidth = 200; var stageheight = 200; var stage = new kinetic.stage({ container: 'container', width: stagewidth, height: stageheight }); container property of stage needs to know the id of the div where we want to show our html5 canvas. initial screen of the game looks like this once our structure is complete… after setting up the environment/structure let’s deal with the user stories / use cases one by one. the main game loop executing after a set interval var gameinterval = self.setinterval(function(){gameloop()},70); setinterval is a javascript function which makes a function called asynchronously that is passed as an argument, after the set intervals. in our case gameloop() is the function which drives the whole game. have a look at it… function gameloop() { if(checkgamestatus()) move(where); else { clearinterval(gameinterval);//stop calling gameloop() alert('game over!'); } } well, the behaviour of gameloop() is pretty obvious. it moves the snake according to the arrow key pressed. and if snake hits himself then display a game over message to the player and also stop the asynchronous calls by calling a javascript clearinterval() method. to capture the arrow keys i have used the jquery’s keydown event handler to respond to the keys pressed. it sets a variable ‘where’ that is eventually used by gameloop() to pass the code to actual move() function. $( document ).ready(function() { $(document).keydown(function(e) { switch(e.keycode) { // user pressed "up" arrow case up_arrow: where = up_arrow; break; // user pressed "down" arrow case down_arrow: where = down_arrow; break; // user pressed "right" arrow case right_arrow: where = right_arrow; break; // user pressed "left" arrow case left_arrow: where = left_arrow; break; } }); }); as you might have guessed already that move() function is actual brain of this game and kinetic.animation handles the actual movement of the objects. all you have to do is to set new locations for your desired objects and then call start() method. to prevent the animation from running infinitely call stop() method immediately after start(). try removing the stop() method and see what happens yourself. function move(direction) { //super hint: only move the tail var foodhit = false; switch(direction) { case down_arrow: foodhit = snakeeatsfood(direction); var anim2 = new kinetic.animation(function(frame) { if(foodhit) { snakehead.sety(snakehead.gety()+10); growsnake(direction); if(snakehead.gety() == stageheight) snakehead.sety(0); relocatefood(); } else { snaketail.sety(snakehead.gety()+10); snaketail.setx(snakehead.getx()); if(snaketail.gety() == stageheight) snaketail.sety(0); reposition(); } }, layer); anim2.start(); anim2.stop(); break; case up_arrow: ... ... move the snake snake is divided into small 10?10-pixels squares. the square on the front is head and the back most square is tail. the technique to move the snake is simple. we pick the tail and put it before the head except when there is only one snake part. the position number assigned to each part of the snake is out of sequence now. head and tail pointers are pointing towards wrong parts. we need to reposition the pointers and position numbers. it is done by calling reposition(). it works as shown in the diagram below… grow the snake when it eats food snake eats food when snake’s head is on the food. once this condition is met, food is relocated to some other cell of the grid. the decision is made inside snakeeatsfood() function. the algorithm used is commonly known as bounding box collision detection for 2d objects. to grow the snake, head moves one step ahead by leaving an empty cell behind. a new rectangle is created at that empty cell to give the impression of the growth of the snake. //grow snake length after eating food function growsnake(direction) { switch(direction) { case down_arrow: var x, y; x = snakehead.getx(); y = snakehead.gety()-10; resetpositions(createsnakepart(x,y)); break; ... ... resetpositions() is almost identical to reposition(), see the detils under "move the snake" heading. assign the food a new location once the snake eats the food, the food is assigned a new location on the grid. relocatefood() performs this function. it prepares a new grid skipping all the positions occupied by the snake. after creating a new grid array, random number generator function generates a number which is used as an index to the grid and eventually we get the coordinates where we can place the food without overlapping the snake. re-enter the snake from the opposite edge when it meets and passes an edge this is really simple. we let snake finish its move, then we check if the head is out of boundary. if it is, we assign it new coordinates to make it appear from the opposite end. the code given below works when snake is moving down, for example… if(snakehead.gety() == stageheight) snakehead.sety(0); end the game when snake hits himself or it occupies the whole ground after each move, checkgamestatus() is called by gameloop() to check if snake has hit himself or not. logic is fairly simple. the same bounding box collision detection method for 2d objects is used here. if coordinates of head matches the coordinates of any other part of the snake, the snake is dead – game end! live demo download in package today we prepared another one good tutorial using kineticjs and html5. i hope you enjoyed our lesson. good luck and welcome back.
June 26, 2013
· 7,652 Views
article thumbnail
Creating Your Own HTML5 Colorwheel
HTML5 Color Picker (canvas) In our new tutorial we are going to create an easy but effective color picker using HTML5. I think that you have already seen different jQuery versions of colorpicker, our goal today is to create something similar, and even better. In order to make it more unique, there are 5 different colorwheels which you can use. If you are ready – let’s start. This would be a good time to test the demos and download the sources: Live Demo 1 Live Demo 2 Live Demo 3 Live Demo 4 Live Demo 5 download in package If you are ready – let’s start coding ! Step 1. HTML Our first step is the html markup: R G B RGB HEX As you see, our color picker consists of two main components: the preview element and the hidden (by default) color picker element. Once we click by preview element – we will display color picker. Step 2. JS Our next step – is javascript. Please review our result code: js/script.js $(function(){ var bCanPreview = true; // can preview // create canvas and context objects var canvas = document.getElementById('picker'); var ctx = canvas.getContext('2d'); // drawing active image var image = new Image(); image.onload = function () { ctx.drawImage(image, 0, 0, image.width, image.height); // draw the image on the canvas } // select desired colorwheel var imagesrc="images/colorwheel1.png"; switch ($(canvas).attr('var')) { case '2': imagesrc="images/colorwheel2.png"; break; case '3': imagesrc="images/colorwheel3.png"; break; case '4': imagesrc="images/colorwheel4.png"; break; case '5': imagesrc="images/colorwheel5.png"; break; } image.src = imageSrc; $('#picker').mousemove(function(e) { // mouse move handler if (bCanPreview) { // get coordinates of current position var canvasOffset = $(canvas).offset(); var canvasX = Math.floor(e.pageX - canvasOffset.left); var canvasY = Math.floor(e.pageY - canvasOffset.top); // get current pixel var imageData = ctx.getImageData(canvasX, canvasY, 1, 1); var pixel = imageData.data; // update preview color var pixelColor = "rgb("+pixel[0]+", "+pixel[1]+", "+pixel[2]+")"; $('.preview').css('backgroundColor', pixelColor); // update controls $('#rVal').val(pixel[0]); $('#gVal').val(pixel[1]); $('#bVal').val(pixel[2]); $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]); var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0]; $('#hexVal').val('#' + ('0000' + dColor.toString(16)).substr(-6)); } }); $('#picker').click(function(e) { // click event handler bCanPreview = !bCanPreview; }); $('.preview').click(function(e) { // preview click $('.colorpicker').fadeToggle("slow", "linear"); bCanPreview = true; }); }); As you can see – there are only 64 lines of our colorpicker, so, as usual, in the beginning we create new canvas and context objects, then – draw an color wheel on the context. As you see – there is small switch case to select desired image (of colorwheel), I decided to use a new attribute for canvas object: ‘var’. So, you can easily change this colorwheel with different ‘var’ value, example: or or or or Well, finally, we have to add event handlers to next events: mousemove (by picker), click (by picker) and click (by preview). As you remember we have to display and hide color picker when we click at Preview element. In order to achieve it – I use ‘fadeToggle’ jQuery function (which was added in version 1.4.4): $('.preview').click(function(e) { // preview click $('.colorpicker').fadeToggle("slow", "linear"); bCanPreview = true; }); When we move our mouse over the Picker object – we should refresh information about current color, and, once we click at the Picker object – we should fix current color (or – disable preview by mousemove): $('#picker').mousemove(function(e) { // mouse move handler if (bCanPreview) { // get coordinates of current position var canvasOffset = $(canvas).offset(); var canvasX = Math.floor(e.pageX - canvasOffset.left); var canvasY = Math.floor(e.pageY - canvasOffset.top); // get current pixel var imageData = ctx.getImageData(canvasX, canvasY, 1, 1); var pixel = imageData.data; // update preview color var pixelColor = "rgb("+pixel[0]+", "+pixel[1]+", "+pixel[2]+")"; $('.preview').css('backgroundColor', pixelColor); // update controls $('#rVal').val(pixel[0]); $('#gVal').val(pixel[1]); $('#bVal').val(pixel[2]); $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]); var dColor = pixel[2] + 256 * pixel[1] + 65536 * pixel[0]; $('#hexVal').val('#' + ('0000' + dColor.toString(16)).substr(-6)); } }); $('#picker').click(function(e) { // click event handler bCanPreview = !bCanPreview; }); Step 3. CSS There are CSS styles of our color picker: /* colorpicker styles */ .colorpicker { background-color: #222222; border-radius: 5px 5px 5px 5px; box-shadow: 2px 2px 2px #444444; color: #FFFFFF; font-size: 12px; position: absolute; width: 460px; } #picker { cursor: crosshair; float: left; margin: 10px; border: 0; } .controls { float: right; margin: 10px; } .controls > div { border: 1px solid #2F2F2F; margin-bottom: 5px; overflow: hidden; padding: 5px; } .controls label { float: left; } .controls > div input { background-color: #121212; border: 1px solid #2F2F2F; color: #DDDDDD; float: right; font-size: 10px; height: 14px; margin-left: 6px; text-align: center; text-transform: uppercase; width: 75px; } .preview { background: url("../images/select.png") repeat scroll center center transparent; border-radius: 3px; box-shadow: 2px 2px 2px #444444; cursor: pointer; height: 30px; width: 30px; } Live Demo 1 Live Demo 2 Live Demo 3 Live Demo 4 Live Demo 5 download in package Conclusion We have just created our own small and effective color picker with HTML5 (canvas). I hope that you like it. I will be glad to see your questions and comments. Good luck!
October 11, 2012
· 44,553 Views · 2 Likes
article thumbnail
CSS3 Games Collection
have you ever thought about creating your own web games? i'm sure that most of you have already heard about the newest technologies like html5, canvas, webgl, and node.js. but i think that before you start working with these new technologies, you should start developing games with the simplest dom (like html, css, and javascript). i would like to provide you with a collection of such games, so you will be able to investigate and try them out. some of them even work without javascript! 1. whack-a-rat – css only game 2. survivor (1982 commodore 64 game remake) 3. sumon 4. 3d – css puzzle 5. duck hunt 6. dino pairs game 7. cops and robbers – css puzzle 8. cascading cube racer 9. css maze puzzle 10. one-of-a-kind css/js-based game portfolio plus, you can find tutorial about making this portfolio here 11. anigma 12. ninja jarimaru conclusion i hope that our new collection of css3 games was interesting for you. good luck!
September 29, 2012
· 64,970 Views · 4 Likes
article thumbnail
CSS3 Fade slider
CSS3 Fade slider Today I would like to show you how to create nice and smooth css3 slider. It uses fade effect to switch between slides. Plus, you can use custom promo text for each slide. We will use basic UL-LI unordered list to make this slider. We don’t need to click anywhere to switch slides – everything is automatically (css3 animation). Live Demo download result So, lets start Step 1. HTML Html markup is very easy. There are four slides. Each slide consists of image (as background) and promo text in DIV. If you need – you always can add more slides here. Promo text #1 Promo text #2 Promo text #3 Promo text #4 Step 2. CSS Now, it’s time to define css styles for our slider. Here are styles for main slider element, inner slides and for promo titles: /* fade slider */ .slides { height:300px; margin:50px auto; overflow:hidden; position:relative; width:900px; } .slides ul { list-style:none; position:relative; } /* keyframes #anim_slides */ @-webkit-keyframes anim_slides { 0% { opacity:0; } 6% { opacity:1; } 24% { opacity:1; } 30% { opacity:0; } 100% { opacity:0; } } @-moz-keyframes anim_slides { 0% { opacity:0; } 6% { opacity:1; } 24% { opacity:1; } 30% { opacity:0; } 100% { opacity:0; } } .slides ul li { opacity:0; position:absolute; top:0; /* css3 animation */ -webkit-animation-name: anim_slides; -webkit-animation-duration: 24.0s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; -moz-animation-name: anim_slides; -moz-animation-duration: 24.0s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; } /* css3 delays */ .slides ul li:nth-child(2), .slides ul li:nth-child(2) div { -webkit-animation-delay: 6.0s; -moz-animation-delay: 6.0s; } .slides ul li:nth-child(3), .slides ul li:nth-child(3) div { -webkit-animation-delay: 12.0s; -moz-animation-delay: 12.0s; } .slides ul li:nth-child(4), .slides ul li:nth-child(4) div { -webkit-animation-delay: 18.0s; -moz-animation-delay: 18.0s; } .slides ul li img { display:block; } /* keyframes #anim_titles */ @-webkit-keyframes anim_titles { 0% { left:100%; opacity:0; } 5% { left:10%; opacity:1; } 20% { left:10%; opacity:1; } 25% { left:100%; opacity:0; } 100% { left:100%; opacity:0; } } @-moz-keyframes anim_titles { 0% { left:100%; opacity:0; } 5% { left:10%; opacity:1; } 20% { left:10%; opacity:1; } 25% { left:100%; opacity:0; } 100% { left:100%; opacity:0; } } .slides ul li div { background-color:#000000; border-radius:10px 10px 10px 10px; box-shadow:0 0 5px #FFFFFF inset; color:#FFFFFF; font-size:26px; left:10%; margin:0 auto; padding:20px; position:absolute; top:50%; width:200px; /* css3 animation */ -webkit-animation-name: anim_titles; -webkit-animation-duration: 24.0s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; -moz-animation-name: anim_titles; -moz-animation-duration: 24.0s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; } You can see that I use two css3 animations here: anim_slides and anim_titles. First one is for separated slides, second one – for promo texts. In order to switch between slides – we change opacity of slides. For titles – we change Left position and opacity too. Live Demo download result Conclusion That is all for today. We have just created new cool pure CSS3-based slider with Fade effect. I hope that you like it. Good luck!
June 21, 2012
· 54,385 Views · 1 Like
article thumbnail
Infographics: Cloud Computing and History
infographic: clouds computing and history i have prepared three new infographics for you;aall of them related with cloud computing. these infographics will tell you about history of cloud computing, its definition, and who needs this cloud. i think that this will be interesting for you. information graphics (known as infographics) are one of the best ways to transfer some information into a reader’s mind. it can be something new, or other useful information gathered in one place. nowadays many people don’t have enough time to read a lot of text on multiple screens. infographics makes the information intuitive and understandable. that’s why we would like to share the best relevant infographics from all over the web. original source: cloud computing by the small business authority original source: a complete history of cloud computing original source: hosting decisions, from the chalkboard
June 6, 2012
· 11,233 Views
article thumbnail
HTML5 Canvas 3D Sphere
our new tutorial tells us how to create an animated 3d sphere (through direct access to pixels on the canvas). the sphere itself moves around the canvas continuously. this example should work in most modern browsers (like firefox, chrome, safari and even in ie). in the end, you should to get something like this: here are our demo and downloadable package: live demo download in package ok, download the source files and let's start coding ! step 1. html this is the markup of our page. index.html i prepared 2 canvas objects here: the first for the source image, and the second one for our sphere. step 2. css css/main.css .container { height: 631px; margin: 50px auto; position: relative; width: 1024px; z-index: 1; } #obj { position: absolute; z-index: 2; } we should put our sphere object above our main canvas. step 3. js js/script.js var canvas, ctx; var canvasobj, ctxobj; var idstw = 256; var idsth = 256; var ixspeed = 4; var iyspeed = 3; var ilastx = idstw / 2; var ilasty = idsth / 2; var oimage; var amap = []; var abitmap; var mathsphere = function(px, py) { var x = px - idstw / 2; var y = py - idsth / 2; var r = math.sqrt(x * x + y * y); var maxr = idstw / 2; if (r > maxr) return {'x':px, 'y':py}; var a = math.atan2(y, x); var k = (r / maxr) * (r / maxr) * 0.5 + 0.5; var dx = math.cos(a) * r * k; var dy = math.sin(a) * r * k; return {'x': dx + idstw / 2, 'y': dy + idsth / 2}; } window.onload = function(){ // load background oimage = new image(); oimage.src="images/bg.jpg"; oimage.onload = function () { // creating canvas and context objects canvas = document.getelementbyid('slideshow'); ctx = canvas.getcontext('2d'); canvasobj = document.getelementbyid('obj'); ctxobj = canvasobj.getcontext('2d'); // clear context ctx.clearrect(0, 0, ctx.canvas.width, ctx.canvas.height); // and draw source image ctx.drawimage(oimage, 0, 0); abitmap = ctx.getimagedata(0, 0, idstw, idsth); for (var y = 0; y < idsth; y++) { for (var x = 0; x < idstw; x++) { var t = mathsphere(x, y); amap[(x + y * idsth) * 2 + 0] = math.max(math.min(t.x, idstw - 1), 0); amap[(x + y * idsth) * 2 + 1] = math.max(math.min(t.y, idsth - 1), 0); } } // begin updating scene updatescene(); }; function updatescene() { // update last coordinates ilastx = ilastx + ixspeed; ilasty = ilasty + iyspeed; // reverse speed if (ilastx > ctx.canvas.width - idstw/2) { ixspeed = -3; } if (ilastx < idstw/2) { ixspeed = 3; } if (ilasty > ctx.canvas.height - idsth/2) { iyspeed = -3; } if (ilasty < idsth/2) { iyspeed = 3; } // shifting of the second object canvasobj.style.left = ilastx - math.floor(idstw / 2) + 'px'; canvasobj.style.top = ilasty - (math.floor(idsth / 2)) + 'px'; // draw result sphere var adata = ctx.getimagedata(ilastx - math.ceil(idstw / 2), ilasty - math.ceil(idsth / 2), idstw, idsth + 1); for (var j = 0; j < idsth; j++) { for (var i = 0; i < idstw; i++) { var u = amap[(i + j * idsth) * 2]; var v = amap[(i + j * idsth) * 2 + 1]; var x = math.floor(u); var y = math.floor(v); var kx = u - x; var ky = v - y; for (var c = 0; c < 4; c++) { abitmap.data[(i + j * idsth) * 4 + c] = (adata.data[(x + y * idsth) * 4 + c] * (1 - kx) + adata.data[((x + 1) + y * idsth) * 4 + c] * kx) * (1-ky) + (adata.data[(x + (y + 1) * idsth) * 4 + c] * (1 - kx) + adata.data[((x + 1) + (y + 1) * idsth) * 4 + c] * kx) * (ky); } } } ctxobj.putimagedata(abitmap,0,0); // update timer settimeout(updatescene, 16); } }; during initialization, the script prepares two canvas objects and two contexts. then, it loads our main background image, and draws it as our first context. then it prepares a hash table of sphere transformations: amap. and, in the end – it starts the timer, which updates the main scene. in this function (updatescene) we update the coordinates of our sphere object, and draw the updated sphere at our second location. live demo download in package conclusion i hope that today’s 3d html5 sphere lesson has been interesting for you. we have done another nice html5 example. i will be glad to see your thanks and comments. good luck!
April 18, 2012
· 11,398 Views
article thumbnail
CSS3 Animated Gears
in today’s lesson, we have made animated gears with css3. the result looks very nice. i have used css3 keyframes, animation and transforms (rotate) in order to achieve this result. please pay attention – the current demo works well only in firefox and chrome / safari (webkit). here are the samples and downloadable package: live demo download in package ok, download the example files and let's start coding ! step 1. html as usual, we start with the html. there are easy div elements. index.html step 2. css here are the css styles of our animated gears. css/layout.css /* css3 keyframes */ @-webkit-keyframes ckw { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); } } @-moz-keyframes ckw { 0% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); } 100% { -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); } } @-webkit-keyframes cckw { 0% { -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); } 100% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); } } @-moz-keyframes cckw { 0% { -moz-transform: rotate(360deg); -webkit-transform: rotate(360deg); } 100% { -moz-transform: rotate(0deg); -webkit-transform: rotate(0deg); } } /* gears */ .gear { float: none; position: absolute; text-align: center; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } #gear1 { background: url('../images/g1.png') no-repeat 0 0; height: 85px; left: 31px; top: 45px; width: 85px; -moz-animation-name: ckw; -moz-animation-duration: 10s; -webkit-animation-name: ckw; -webkit-animation-duration: 10s; } #gear2 { background: url('../images/g2.png') no-repeat 0 0; height: 125px; left: 105px; top: 10px; width: 125px; -moz-animation-name: cckw; -moz-animation-duration: 16.84s; -webkit-animation-name: cckw; -webkit-animation-duration: 16.84s; } #gear3 { background: url('../images/g3.png') no-repeat 0 0; height: 103px; left: 149px; top: 118px; width: 103px; -moz-animation-name: ckw; -moz-animation-duration: 13.5s; -webkit-animation-name: ckw; -webkit-animation-duration: 13.5s; } #gear4 { background: url('../images/g4.png') no-repeat 0 0; height: 144px; left: 46px; top: 173px; width: 144px; -moz-animation-name: cckw; -moz-animation-duration: 20.2s; -webkit-animation-name: cckw; -webkit-animation-duration: 20.2s; } #gear5 { background: url('../images/g1.png') no-repeat 0 0; height: 85px; left: 127px; top: 292px; width: 85px; -moz-animation-name: ckw; -moz-animation-duration: 10s; -webkit-animation-name: ckw; -webkit-animation-duration: 10s; } #gear6 { background: url('../images/g2.png') no-repeat 0 0; height: 125px; left: 200px; top: 283px; width: 125px; -moz-animation-name: cckw; -moz-animation-duration: 16.84s; -webkit-animation-name: cckw; -webkit-animation-duration: 16.84s; } #gear7 { background: url('../images/g3.png') no-repeat 0 0; height: 103px; left: 277px; top: 217px; width: 103px; -moz-animation-name: ckw; -moz-animation-duration: 13.5s; -webkit-animation-name: ckw; -webkit-animation-duration: 13.5s; } step 3. images i have used these images: live demo download in package conclusion hope you enjoyed the new tutorial, don’t forget to give thanks and leave a comment good luck!
March 25, 2012
· 22,798 Views
article thumbnail
HTML5 Image Effects – Emboss
Today we continue our HTML5 canvas image filter examples. Today I would like to share with you a method of applying a Emboss effect to images. This is a pretty difficult method, but I am sure that you can repeat it. In our demo we can play with different images by adding an emboss effect to them, and we can ‘export’ our result on the image element (). Here are our demo and downloadable packages: Live Demo download in package Ok, download the example files and let's start coding ! Step 1. HTML Markup This is the markup of our demo page: index.html HTML5 Image Effects - Emboss Back to original tutorial on Script Tutorials Canvas Object Image Object Next image Apply Emboss Effect To Image Basically – it contains just one canvas object, one image, and three ‘buttons’ (div elements). Step 2. CSS Here are our stylesheets (not so important, but anyway): css/main.css *{ margin:0; padding:0; } body { background-image:url(../images/bg.png); color:#fff; font:14px/1.3 Arial,sans-serif; } header { background-color:#212121; box-shadow: 0 -1px 2px #111111; display:block; height:70px; position:relative; width:100%; z-index:100; } header h2{ font-size:22px; font-weight:normal; left:50%; margin-left:-400px; padding:22px 0; position:absolute; width:540px; } header a.stuts,a.stuts:visited { border:none; text-decoration:none; color:#fcfcfc; font-size:14px; left:50%; line-height:31px; margin:23px 0 0 110px; position:absolute; top:0; } header .stuts span { font-size:22px; font-weight:bold; margin-left:5px; } .container { color: #000000; margin: 20px auto; overflow: hidden; position: relative; width: 1005px; } table { background-color: rgba(255, 255, 255, 0.7); } table td { border: 1px inset #888888; position: relative; text-align: center; } table td p { display: block; padding: 10px 0; } .button { cursor: pointer; height: 20px; padding: 15px 0; position: relative; text-align: center; width: 500px; -moz-user-select: none; -khtml-user-select: none; user-select: none; } Step 3. JS Finally – our JavaScript code for the Emboss effect: js/script.js // variables var canvas, ctx; var imgObj; // filter strength var strength = 0.5; // shifting matrix var matrix = [-2, -1, 0, -1, 1, 1, 0, 1, 2]; // normalize matrix function normalizeMatrix(m) { var j = 0; for (var i = 0; i < m.length; i++) { j += m[i]; } for (var i = 0; i < m.length; i++) { m[i] /= j; } return m; } // convert x-y coordinates into pixel position function convertCoordinates(x, y, w) { return x + (y * w); } // find a specified distance between two colours function findColorDiff(dif, dest, src) { return dif * dest + (1 - dif) * src; } // transform matrix function transformMatrix(img, pixels) { // create a second canvas and context to keep temp results var canvas2 = document.createElement('canvas'); var ctx2 = canvas2.getContext('2d'); ctx2.width = canvas2.width = img.width; ctx2.height = canvas2.height = img.height; // draw image ctx2.drawImage(img, 0, 0, img.width , img.height); var buffImageData = ctx2.getImageData(0, 0, canvas.width, canvas.height); var data = pixels.data; var bufferedData = buffImageData.data; // normalize matrix matrix = normalizeMatrix(matrix); var mSize = Math.sqrt(matrix.length); for (var i = 1; i < img.width - 1; i++) { for (var j = 1; j < img.height - 1; j++) { var sumR = sumG = sumB = 0; // loop through the matrix for (var h = 0; h < mSize; h++) { for (var w = 0; w < mSize; w++) { var r = convertCoordinates(i + h - 1, j + w - 1, img.width) << 2; // RGB for current pixel var currentPixel = { r: bufferedData[r], g: bufferedData[r + 1], b: bufferedData[r + 2] }; sumR += currentPixel.r * matrix[w + h * mSize]; sumG += currentPixel.g * matrix[w + h * mSize]; sumB += currentPixel.b * matrix[w + h * mSize]; } } var rf = convertCoordinates(i, j, img.width) << 2; data[rf] = findColorDiff(strength, sumR, data[rf]); data[rf + 1] = findColorDiff(strength, sumG, data[rf + 1]); data[rf + 2] = findColorDiff(strength, sumB, data[rf + 2]); } } return pixels; } // process emboss function function processEmboss() { // clear context ctx.clearRect(0, 0, canvas.width, canvas.height); // draw image ctx.drawImage(imgObj, 0, 0, imgObj.width , imgObj.height); // get image data var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); // transform image data imageData = transformMatrix(imgObj, imageData); // draw data back ctx.putImageData(imageData, 0, 0); }; $(function () { // create canvas and context objects canvas = document.getElementById('source'); ctx = canvas.getContext('2d'); // load source image imgObj = new Image(); imgObj.onload = function () { // draw image ctx.drawImage(this, 0, 0, this.width, this.height, 0, 0, canvas.width, canvas.height); } imgObj.src="images/pic1.jpg"; // different onclick handlers var iCur = 1; $('#next').click(function () { iCur++; if (iCur > 6) iCur = 1; imgObj.src="images/pic" + iCur + '.jpg'; }); $('#emboss').click(function () { processEmboss(); }); $('#toImage').click(function () { $('#img').attr('src', canvas.toDataURL('image/jpeg')); }); }); This effect requires some pretty difficult matrix transformations, so you can try to understand it, or use it as-is. Of course, our script will pass through all the pixels of the original image, and then will apply some transformations. Live Demo download in package Conclusion I hope that our demo looks fine. Today we have added a new interesting effect to our html5 application – Emboss. I will be glad to see your thanks and comments. Good luck!
March 20, 2012
· 12,510 Views
article thumbnail
HTML5 Image Effects: Sepia
Today we continue our HTML5 canvas examples. Today I want to share with you a method of applying a sepia effect to images. This is not a very difficult method, anyone can repeat it. In our demo we can play with different images by adding a sepia effect to them, as well as ‘export’ our result on the image element (). Here are our demo and downloadable package: Live Demo download in package Ok, download the example files and lets start coding ! Step 1. HTML Markup This is the markup of our demo page. Here it is: index.html HTML5 Image Effects - Sepia Back to original tutorial on Script Tutorials Canvas Object Image Object Next image Apply Sepia Effect To Image Basically – it contains just one canvas object, one image, and three ‘buttons’ (div elements). Step 2. CSS Here are our stylesheets: css/main.css *{ margin:0; padding:0; } body { background-image:url(../images/bg.png); color:#fff; font:14px/1.3 Arial,sans-serif; } header { background-color:#212121; box-shadow: 0 -1px 2px #111111; display:block; height:70px; position:relative; width:100%; z-index:100; } header h2{ font-size:22px; font-weight:normal; left:50%; margin-left:-400px; padding:22px 0; position:absolute; width:540px; } header a.stuts,a.stuts:visited { border:none; text-decoration:none; color:#fcfcfc; font-size:14px; left:50%; line-height:31px; margin:23px 0 0 110px; position:absolute; top:0; } header .stuts span { font-size:22px; font-weight:bold; margin-left:5px; } .container { color: #000000; margin: 20px auto; overflow: hidden; position: relative; width: 1005px; } table { background-color: rgba(255, 255, 255, 0.7); } table td { border: 1px inset #888888; position: relative; text-align: center; } table td p { display: block; padding: 10px 0; } .button { cursor: pointer; height: 20px; padding: 15px 0; position: relative; text-align: center; width: 500px; -moz-user-select: none; -khtml-user-select: none; user-select: none; } Step 3. JS Finally – our Javascript code generating the sepia effect: js/script.js // variables var canvas, ctx; var imgObj; // set of sepia colors var r = [0, 0, 0, 1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 17, 18, 19, 19, 20, 21, 22, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 44, 45, 47, 48, 49, 52, 54, 55, 57, 59, 60, 62, 65, 67, 69, 70, 72, 74, 77, 79, 81, 83, 86, 88, 90, 92, 94, 97, 99, 101, 103, 107, 109, 111, 112, 116, 118, 120, 124, 126, 127, 129, 133, 135, 136, 140, 142, 143, 145, 149, 150, 152, 155, 157, 159, 162, 163, 165, 167, 170, 171, 173, 176, 177, 178, 180, 183, 184, 185, 188, 189, 190, 192, 194, 195, 196, 198, 200, 201, 202, 203, 204, 206, 207, 208, 209, 211, 212, 213, 214, 215, 216, 218, 219, 219, 220, 221, 222, 223, 224, 225, 226, 227, 227, 228, 229, 229, 230, 231, 232, 232, 233, 234, 234, 235, 236, 236, 237, 238, 238, 239, 239, 240, 241, 241, 242, 242, 243, 244, 244, 245, 245, 245, 246, 247, 247, 248, 248, 249, 249, 249, 250, 251, 251, 252, 252, 252, 253, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], g = [0, 0, 1, 2, 2, 3, 5, 5, 6, 7, 8, 8, 10, 11, 11, 12, 13, 15, 15, 16, 17, 18, 18, 19, 21, 22, 22, 23, 24, 26, 26, 27, 28, 29, 31, 31, 32, 33, 34, 35, 35, 37, 38, 39, 40, 41, 43, 44, 44, 45, 46, 47, 48, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 63, 64, 65, 66, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 79, 80, 81, 83, 84, 85, 86, 88, 89, 90, 92, 93, 94, 95, 96, 97, 100, 101, 102, 103, 105, 106, 107, 108, 109, 111, 113, 114, 115, 117, 118, 119, 120, 122, 123, 124, 126, 127, 128, 129, 131, 132, 133, 135, 136, 137, 138, 140, 141, 142, 144, 145, 146, 148, 149, 150, 151, 153, 154, 155, 157, 158, 159, 160, 162, 163, 164, 166, 167, 168, 169, 171, 172, 173, 174, 175, 176, 177, 178, 179, 181, 182, 183, 184, 186, 186, 187, 188, 189, 190, 192, 193, 194, 195, 195, 196, 197, 199, 200, 201, 202, 202, 203, 204, 205, 206, 207, 208, 208, 209, 210, 211, 212, 213, 214, 214, 215, 216, 217, 218, 219, 219, 220, 221, 222, 223, 223, 224, 225, 226, 226, 227, 228, 228, 229, 230, 231, 232, 232, 232, 233, 234, 235, 235, 236, 236, 237, 238, 238, 239, 239, 240, 240, 241, 242, 242, 242, 243, 244, 245, 245, 246, 246, 247, 247, 248, 249, 249, 249, 250, 251, 251, 252, 252, 252, 253, 254, 255], b = [53, 53, 53, 54, 54, 54, 55, 55, 55, 56, 57, 57, 57, 58, 58, 58, 59, 59, 59, 60, 61, 61, 61, 62, 62, 63, 63, 63, 64, 65, 65, 65, 66, 66, 67, 67, 67, 68, 69, 69, 69, 70, 70, 71, 71, 72, 73, 73, 73, 74, 74, 75, 75, 76, 77, 77, 78, 78, 79, 79, 80, 81, 81, 82, 82, 83, 83, 84, 85, 85, 86, 86, 87, 87, 88, 89, 89, 90, 90, 91, 91, 93, 93, 94, 94, 95, 95, 96, 97, 98, 98, 99, 99, 100, 101, 102, 102, 103, 104, 105, 105, 106, 106, 107, 108, 109, 109, 110, 111, 111, 112, 113, 114, 114, 115, 116, 117, 117, 118, 119, 119, 121, 121, 122, 122, 123, 124, 125, 126, 126, 127, 128, 129, 129, 130, 131, 132, 132, 133, 134, 134, 135, 136, 137, 137, 138, 139, 140, 140, 141, 142, 142, 143, 144, 145, 145, 146, 146, 148, 148, 149, 149, 150, 151, 152, 152, 153, 153, 154, 155, 156, 156, 157, 157, 158, 159, 160, 160, 161, 161, 162, 162, 163, 164, 164, 165, 165, 166, 166, 167, 168, 168, 169, 169, 170, 170, 171, 172, 172, 173, 173, 174, 174, 175, 176, 176, 177, 177, 177, 178, 178, 179, 180, 180, 181, 181, 181, 182, 182, 183, 184, 184, 184, 185, 185, 186, 186, 186, 187, 188, 188, 188, 189, 189, 189, 190, 190, 191, 191, 192, 192, 193, 193, 193, 194, 194, 194, 195, 196, 196, 196, 197, 197, 197, 198, 199]; // noise value var noise = 20; function processSepia() { // get current image data var imageData = ctx.getImageData(0,0,canvas.width,canvas.height); for (var i=0; i < imageData.data.length; i+=4) { // change image colors imageData.data[i] = r[imageData.data[i]]; imageData.data[i+1] = g[imageData.data[i+1]]; imageData.data[i+2] = b[imageData.data[i+2]]; // apply noise if (noise > 0) { var noise = Math.round(noise - Math.random() * noise); for(var j=0; j<3; j++){ var iPN = noise + imageData.data[i+j]; imageData.data[i+j] = (iPN > 255) ? 255 : iPN; } } } // put image data back to context ctx.putImageData(imageData, 0, 0); }; $(function () { // create canvas and context objects canvas = document.getElementById('source'); ctx = canvas.getContext('2d'); // load source image imgObj = new Image(); imgObj.onload = function () { // draw image ctx.drawImage(this, 0, 0, this.width, this.height, 0, 0, canvas.width, canvas.height); } imgObj.src="images/pic1.jpg"; // different onclick handlers var iCur = 1; $('#next').click(function () { iCur++; if (iCur > 6) iCur = 1; imgObj.src="images/pic" + iCur + '.jpg'; }); $('#sepia').click(function () { processSepia(); }); $('#toImage').click(function () { $('#img').attr('src', canvas.toDataURL('image/jpeg')); }); }); Main idea: as we know – sepia images have their own, quite predefined colors. So our script will walk through all pixels of the original image, and change the pixel color to the corresponding sepia color. Plus, we will add a little of noise to our image. Live Demo download in package Conclusion I hope that our demo looks fine. Today we have added a new interesting effect to our html5 application – Sepia. I will be glad to see your thanks and comments. Good luck!
March 2, 2012
· 11,069 Views
article thumbnail
Streaming Radio Player Tutorial with Live Demo and Source Code
today i have prepared another really great tutorial for you. recently i started development of my own radio software (as a module for dolphin cms) and got some interesting results i would like to share with you. it will be nice looking (css3) radio script that consists of three main elements: the header (with animated search bar and integrated radio player), the left side (with a list of categories and subcategories) and the right side (which will contain a list of recent or filtered stations). here's the final result of our player: here's our live demo and downloadable package: ok, download our source files and lets start coding! step 1. html markup this is the markup of one of the template files. this is a template of our main (index) page: templates/main_page.html stream radio script back to original tutorial on script tutorials alternative classic alternative industrial new wave punk classical modern opera piano romantic symphony electronic breakbeat dance electro house techno trance metal classic metal heavy metal metalcore power metal pop dance pop oldies top 40 world pop __stations__ powered by script tutorials first, pay attention to how the script loads the jquery library from google. this can be pretty useful if you don’t like to keep this file directly on your host. our header element contains a nice search bar with an embedded jasl player ( i used a great ffmp3 live stream player ), which allows us to play audio streams without any problems. next, on the left-hand side (beneath the header) we have a ul-li based list of categories and subcategories. the right-hand side will contain a list of the most recent stations and, when we search or select a category, the right-hand side will be filtered by ajaxy. for now – it contains __stations__ key (template key) and we will replace the actual value with php. on to our next template file, the radio player: templates/radio.html of course, it contains its own template keys (__title__ and __stream__) which we will use after. step 2. css here are our stylesheets files: css/main.css the first one contains the styles of our test page (this file is always available in our package) css/radio.css /* header area */ .header { height:62px; } .header input { background:#aaa url(../images/search.png) no-repeat 5px center; border:1px solid #888; border-radius:10px; float:right; margin:14px 10px 0 0; outline:none; padding-left:20px; width:200px; -webkit-transition: 0.5s; -moz-transition: 0.5s; -o-transition: 0.5s; transition: 0.5s; } .header input:focus { background-color:#eee; width:300px; } .header > span { display:block; float:left; line-height:40px; padding:7px; -webkit-transition: 0.5s; -moz-transition: 0.5s; -o-transition: 0.5s; transition: 0.5s; } /* stations list */ .stlist { float:right; margin-right:1%; width:71%; } .stlist ul { list-style:none outside none; margin:0; padding:0; } .stlist ul li { border-bottom:1px dotted #444; overflow:hidden; padding:10px; } .stlist ul li > a > img { border:1px solid #ccc; float:left; height:85px; margin-right:15px; padding:1px; width:85px; } .stlist ul li > div { float:right; margin-left:15px; margin-top:-5px; } .stlist ul li > p.label,.stlist ul li > p.track { font-size:11px; font-weight:700; } .stlist ul li > p.label { color:#888; } .stlist ul li > p.channel { font-size:14px; font-weight:700; margin-bottom:17px; } /* genres list */ .genres_par { border-right:1px solid #ccc; float:left; width:26%; } ul.genres,ul.genres ul { list-style-type:none; margin:0; padding:0; } ul.genres ul { display:none; overflow:hidden; padding:0 15px; } ul.genres ul li { margin:3px; } ul.genres a { color:#333; display:block; font-size:18px; padding:4px 0; text-align:center; text-decoration:none; } ul.genres ul a { font-size:12px; text-align:left; } ul.genres li { border-bottom:1px solid #ccc; margin:0; } ul.genres li ul li a { background:none repeat scroll 0 0 #5bb951; border-radius:2px; color:#fff; font-size:12px; padding:6px; } ul.genres li ul li a:hover { background-color:#53854e; } step 3. js js/script.js $(document).ready(function(){ $('#search').blur(function() { if ('' == $('#search').val()) $('#search').val('search'); }); $('#search').focus(function() { if ('search' == $('#search').val()) $('#search').val(''); }); $('ul.genres li a').click( // category slider function() { var checkelement = $(this).next(); if((checkelement.is('ul')) && (!checkelement.is(':visible'))) { $('.genres li ul').slideup(150); $(this).next().slidetoggle(150); } } ); $('ul.genres ul li a').click( // get stations by category function() { $.ajax({ type: 'get', url: 'index.php', data: 'action=get_genre_stations&id=' + $(this).parent().attr('id') + '&name=' + $(this).parent().attr('val'), success: function(data){ $('.stlist').fadeout(400, function () { $('.stlist').html(data); $('.stlist').fadein(400); }); } }); } ); }); function play(id) { // play function $('#rplayer').load('index.php?action=play&id=' + id, function() {}); return false; } function get_stations_by_keyword() { // get stations by keyword var keyword = $('#search').val().replace(/ /g,"+"); $.ajax({ type: 'get', url: 'index.php', data: 'action=get_keyword_stations&key=' + keyword, success: function(data){ $('.stlist').fadeout(400, function () { $('.stlist').html(data); $('.stlist').fadein(400); }); } }); } as you see – there's nothing difficult there. just several event handlers, and two new functions (to play radio station and to search for stations by keyword). step 4. php index.php =') == 1) error_reporting(e_all & ~e_notice & ~e_deprecated); else error_reporting(e_all & ~e_notice); $astations = array( 0 => array( 'category' => 31, 'name' => 'eurodance', 'desc' => 'the newest and best of eurodance hits', 'url' => 'http://www.di.fm/eurodance', 'br' => 96, 'stream' => 'http://scfire-mtc-aa06.stream.aol.com:80/stream/1024' ), 1 => array ( 'category' => 34, 'name' => 'house', 'desc' => 'silky sexy deep house music direct from new york city!', 'url' => 'http://www.di.fm/house', 'br' => 96, 'stream' => 'http://scfire-ntc-aa04.stream.aol.com:80/stream/1007' ), 2 => array ( 'category' => 13, 'name' => 'trance', 'desc' => 'the hottest, freshest trance music from around the globe!', 'url' => 'http://www.di.fm/trance', 'br' => 96, 'stream' => 'http://scfire-ntc-aa04.stream.aol.com:80/stream/1003' ), 3 => array ( 'category' => 51, 'name' => 'electro house', 'desc' => 'an eclectic mix of electro and dirty house', 'url' => 'http://www.di.fm/electro', 'br' => 96, 'stream' => 'http://scfire-ntc-aa04.stream.aol.com:80/stream/1025' ) ); function searchbycat($icat, $astations) { $ares = array(); foreach ($astations as $i => $ainfo) { if ($ainfo['category'] == $icat) { $ares[$i] = $ainfo; } } return $ares; } function searchbykeyword($skey, $astations) { $ares = array(); foreach ($astations as $i => $ainfo) { if (false !== strpos($ainfo['name'], $skey) || false !== strpos($ainfo['desc'], $skey)) { $ares[$i] = $ainfo; } } return $ares; } function parsestationlist($adata) { $sstations = ''; if (is_array($adata) && count($adata) > 0) { foreach ($adata as $i => $a) { $sstationid = $i; $sstationbr = (int)$a['br']; $sstationname = $a['name']; $sstationdesc = $a['desc']; $sstationurl = $a['url']; $sthumb = 'media/'.($sstationid+1).'.png'; $sstations .= << bitrate: {$sstationbr} {$sstationname} {$sstationdesc} {$sstationurl} eof; } } $sstations = ($sstations == '') ? 'nothing found' : $sstations; return '' . $sstations . ''; } switch ($_get['action']) { case 'play': $i = (int)$_get['id']; $ainfo = $astations[$i]; $avars = array ( '__stream__' => $ainfo['stream'], '__title__' => $ainfo['name'] ); echo strtr(file_get_contents('templates/radio.html'), $avars); exit; break; case 'get_genre_stations': $i = (int)$_get['id']; $asearch = searchbycat($i, $astations); $sstations = parsestationlist($asearch); header('content-type: text/html; charset=utf-8'); echo $sstations; exit; break; case 'get_keyword_stations': $skey = $_get['key']; $asearch = searchbykeyword($skey, $astations); $sstations = parsestationlist($asearch); header('content-type: text/html; charset=utf-8'); echo $sstations; exit; break; } $slaststations = parsestationlist($astations); echo strtr(file_get_contents('templates/main_page.html'), array('__stations__' => $slaststations)); at the beginning, i have prepared a list of our radio stations (4 stations total). then, two search functions: ‘searchbycat’ and ‘searchbykeyword’. next, the special function ‘parsestationlist’ which will transform array with filtered stations into its html representation. finally, a little switch case to manage with our inner ajax commands. conclusion you are always welcome to enhance our script and share your ideas. i will be glad to see your thanks and comments. good luck!
February 29, 2012
· 50,468 Views · 1 Like
article thumbnail
HTML5 Canvas Slideshow
In this tutorial we are making a HTML5 Slideshow (canvas) with its own animated transitioning effect. The main idea is: drawing images with higher contrast in the ends of transitions. Here are our demo and downloadable packages: Live Demo download in package Ok, download the source files and let's start coding ! Step 1. HTML This is the markup of our resulting slideshow page. index.html HTML5 Canvas Slideshow Back to original tutorial on Script Tutorials Step 2. CSS Here are all the stylesheets: css/main.css /* page layout styles */ *{ margin:0; padding:0; } body { background-color:#eee; color:#fff; font:14px/1.3 Arial,sans-serif; } header { background-color:#212121; box-shadow: 0 -1px 2px #111111; display:block; height:70px; position:relative; width:100%; z-index:100; } header h2{ font-size:22px; font-weight:normal; left:50%; margin-left:-400px; padding:22px 0; position:absolute; width:540px; } header a.stuts,a.stuts:visited{ border:none; text-decoration:none; color:#fcfcfc; font-size:14px; left:50%; line-height:31px; margin:23px 0 0 110px; position:absolute; top:0; } header .stuts span { font-size:22px; font-weight:bold; margin-left:5px; } .container { color: #000; margin: 20px auto; position: relative; width: 900px; } #slideshow { border:1px #000 solid; box-shadow:4px 6px 6px #444444; display:block; margin:0 auto; height:300px; width:900px; } .container .slides { display:none; } Step 3. JS js/pixastic.custom.js Pixastic – JavaScript Image Processing Library. I have used it to change the brightness and contrast of our canvas. You can download this library here. Or, you can find this library in our package too. js/script.js var canvas, ctx; var aImages = []; var iCurSlide = 0; var iCnt = 0; var iSmTimer = 0; var iContr = 0; var iEfIter = 50; $(function(){ // creating canvas objects canvas = document.getElementById('slideshow'); ctx = canvas.getContext('2d'); // collect all images $('.slides').children().each(function(i){ var oImg = new Image(); oImg.src = this.src; aImages.push(oImg); }); // draw first image ctx.drawImage(aImages[iCurSlide], 0, 0); var iTimer = setInterval(changeSlideTimer, 5000); // set inner timer }); function changeSlideTimer() { iCurSlide++; if (iCurSlide == $(aImages).length) { iCurSlide = 0; } clearInterval(iSmTimer); iSmTimer = setInterval(drawSwEffect, 40); // extra one timer } // draw switching effect function drawSwEffect() { iCnt++; if (iCnt <= iEfIter / 2) { iContr += 0.004; // change brightness and contrast Pixastic.process(canvas, 'brightness', { 'brightness': 2, 'contrast': 0.0 + iContr, 'leaveDOM': true }, function(img) { ctx.drawImage(img, 0, 0); } ); } if (iCnt > iEfIter / 2) { // change brightness Pixastic.process(canvas, 'brightness', { 'brightness': -2, 'contrast': 0, 'leaveDOM': true }, function(img) { ctx.drawImage(img, 0, 0); } ); } if (iCnt == iEfIter / 2) { // switch actual image iContr = 0; ctx.drawImage(aImages[iCurSlide], 0, 0); Pixastic.process(canvas, 'brightness', { 'brightness': iEfIter, 'contrast': 0, 'leaveDOM': true }, function(img) { ctx.drawImage(img, 0, 0); } ); } else if (iCnt == iEfIter) { // end of cycle, clear extra sub timer clearInterval(iSmTimer); iCnt = 0; iContr = 0; } } As you can see – the main functionality is easy. I have defined the main timer (which will change images), and one inner timer, which will change the brightness and contrast of our canvas. Live Demo download in package Conclusion I hope that today’s html5 slideshow lesson was interesting for you as always. We have made another nice html5 example. I will be glad to see your thanks and comments. Good luck! Source: http://www.script-tutorials.com/html5-canvas-slideshow/
January 25, 2012
· 16,373 Views
article thumbnail
Spinning Images in WebGL
today we continue html5 canvas examples. and today is our second tutorial for webgl. we will be creating animated twisting images. also we will add handlers to manipulate the images with mouse and keyboard. here are our demo and downloadable package: live demo download in package ok, download the example files and lets start coding ! step 1. html here are html sources of our demo. as you can see – just an empty page. index.html creating a keyboard sensitive 3d twisted images in webgl | script tutorials you can use your mouse + arrow keys + page up / down step 2. css here are used css styles. css/main.css body { background:#eee; font-family:verdana, helvetica, arial, sans-serif; margin:0; padding:0 } .example { background:#fff; width:500px; font-size:80%; border:1px #000 solid; margin:20px auto; padding:15px; position:relative; -moz-border-radius: 3px; -webkit-border-radius:3px } h3 { text-align:center; } step 3. js js/webgl-utils.js and js/glmatrix-0.9.5.min.js these files we will use in project for working with webgl. both files will in our package. js/script.js var gl; // global webgl object var shaderprogram; var pics_names=['1.png', '2.png', '3.png', '4.png', '5.png', '6.png', '7.png']; var pics_num=pics_names.length; // diffirent initializations function initgl(canvas) { try { gl = canvas.getcontext('experimental-webgl'); gl.viewportwidth = canvas.width; gl.viewportheight = canvas.height; } catch (e) {} if (! gl) { alert('can`t initialise webgl, not supported'); } } function getshader(gl, type) { var str = ''; var shader; if (type == 'x-fragment') { str = "#ifdef gl_es\n"+ "precision highp float;\n"+ "#endif\n"+ "varying vec2 vtexturecoord;\n"+ "uniform sampler2d usampler;\n"+ "void main(void) {\n"+ " gl_fragcolor = texture2d(usampler, vec2(vtexturecoord.s, vtexturecoord.t));\n"+ "}\n"; shader = gl.createshader(gl.fragment_shader); } else if (type == 'x-vertex') { str = "attribute vec3 avertexposition;\n"+ "attribute vec2 atexturecoord;\n"+ "uniform mat4 umvmatrix;\n"+ "uniform mat4 upmatrix;\n"+ "varying vec2 vtexturecoord;\n"+ "void main(void) {\n"+ " gl_position = upmatrix * umvmatrix * vec4(avertexposition, 1.0);\n"+ " vtexturecoord = atexturecoord;\n"+ "}\n"; shader = gl.createshader(gl.vertex_shader); } else { return null; } gl.shadersource(shader, str); gl.compileshader(shader); if (!gl.getshaderparameter(shader, gl.compile_status)) { alert(gl.getshaderinfolog(shader)); return null; } return shader; } function initshaders() { var fragmentshader = getshader(gl, 'x-fragment'); var vertexshader = getshader(gl, 'x-vertex'); shaderprogram = gl.createprogram(); gl.attachshader(shaderprogram, vertexshader); gl.attachshader(shaderprogram, fragmentshader); gl.linkprogram(shaderprogram); if (!gl.getprogramparameter(shaderprogram, gl.link_status)) { alert('can`t initialise shaders'); } gl.useprogram(shaderprogram); shaderprogram.vertexpositionattribute = gl.getattriblocation(shaderprogram, 'avertexposition'); gl.enablevertexattribarray(shaderprogram.vertexpositionattribute); shaderprogram.texturecoordattribute = gl.getattriblocation(shaderprogram, 'atexturecoord'); gl.enablevertexattribarray(shaderprogram.texturecoordattribute); shaderprogram.pmatrixuniform = gl.getuniformlocation(shaderprogram, 'upmatrix'); shaderprogram.mvmatrixuniform = gl.getuniformlocation(shaderprogram, 'umvmatrix'); shaderprogram.sampleruniform = gl.getuniformlocation(shaderprogram, 'usampler'); } var objvertexpositionbuffer=new array(); var objvertextexturecoordbuffer=new array(); var objvertexindexbuffer=new array(); function initobjbuffers() { for (var i=0;i
January 15, 2012
· 7,930 Views
article thumbnail
CSS3 Optical Illusions
today i have prepared something interesting for you. this is a demonstration of several optical illusions in css3 (without using any images or javascript). enjoy the results. here are samples and downloadable package: live demo download in package ok, download the example files and let's start coding! step 1. html as usual, we start with the html. here is full html code of all 6 demos. index.html css3 optical illusions back to original tutorial on script tutorials 1 2 3 4 5 6 38 38 step 2. css here are the css styles. maybe you’ve noticed that in our html i have two css files: layout.css and illusions.css. the first file (layout.css) contain the styles of our test page. we will not publish these styles in this article, but if you wish – you can find these styles in our package. css/illusions.css span { display: none; } .contr { color: #000000; cursor: pointer; float: left; font-size: 16px; font-weight: bold; height: 30px; line-height: 30px; margin: 10px; text-align: center; text-decoration: none; width: 60px; -webkit-border-radius:10px; -moz-border-radius:10px; -ms-border-radius:10px; -o-border-radius:10px; border-radius:10px; background-color:#e3e3ff; background: -moz-linear-gradient(#ffffff, #eee); background: -ms-linear-gradient(#ffffff, #eee); background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #eee)); background: -webkit-linear-gradient(#ffffff, #eee); background: -o-linear-gradient(#ffffff, #eee); filter: progid:dximagetransform.microsoft.gradient(startcolorstr='#ffffff', endcolorstr='#eee'); -ms-filter: "progid:dximagetransform.microsoft.gradient(startcolorstr='#ffffff', endcolorstr='#eee')"; background: linear-gradient(#ffffff, #eee); } .contr:hover{ background-color:#e3e3ff; box-shadow:0px 0px 4px rgba(0,0,0,0.5) inset, 0px 0px 0px 4px rgba(51,51,204,0.5); -moz-box-shadow:0px 0px 4px rgba(0,0,0,0.5) inset, 0px 0px 0px 4px rgba(51,51,204,0.5); -webkit-box-shadow:0px 0px 4px rgba(0,0,0,0.5) inset, 0px 0px 0px 4px rgba(51,51,204,0.5); } .demos { background-color: #b2b2b2; display: block; height: 640px; margin-top: 55px; overflow: hidden; position: relative; } .demos > div { display: none; } #page1:target ~ .demos #i1 { display: block; } #page2:target ~ .demos #i2 { display: block; } #page3:target ~ .demos #i3 { display: block; } #page4:target ~ .demos #i4 { display: block; } #page5:target ~ .demos #i5 { display: block; } #page6:target ~ .demos #i6 { display: block; } /* illusion 1 */ #i1 { width: 900px; } #i1 .row { background-color: #fff; border-bottom: 2px solid #888; height: 90px; -webkit-background-size: 140px 70px; -moz-background-size: 140px 70px; -ms-background-size: 140px 70px; -o-background-size: 140px 70px; background-size: 140px 70px; background-position: 0 50%; background-image: -webkit-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -moz-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -ms-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -o-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: linear-gradient(0deg, #000 50%, transparent 50%, transparent); } #i1 .row:nth-child(3n+3) { background-position: 60px 50%; } #i1 .row:nth-child(2n+2) { background-position: 30px 50%; } /* illusion 2 */ #i2 { background-color: #98cb00; height: 640px; margin: 0 auto; overflow: hidden; padding: 0 150px; position: relative; width: 600px; } #i2 > div { float: left; height: 105px; padding-left: 90px; padding-top: 90px; position: relative; width: 105px; } #i2 div div { border: 1px outset #fff; height: 20px; position: absolute; width: 30px; -webkit-border-radius: 100px / 50px; -moz-border-radius: 100px / 50px; -ms-border-radius: 100px / 50px; -o-border-radius: 100px / 50px; border-radius: 100px / 50px; background: -webkit-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: -moz-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: -ms-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: -o-linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); background: linear-gradient(top, #580402, #a63b17, #580402, #a63b17, #580402); } #i2 #o1 { -webkit-transform: rotate(-30deg) translatex(70px); -moz-transform: rotate(-30deg) translatex(70px); -ms-transform: rotate(-30deg) translatex(70px); -o-transform: rotate(-30deg) translatex(70px); transform: rotate(-30deg) translatex(70px); } #i2 #o2 { -webkit-transform: rotate(-60deg) translatex(70px); -moz-transform: rotate(-60deg) translatex(70px); -ms-transform: rotate(-60deg) translatex(70px); -o-transform: rotate(-60deg) translatex(70px); transform: rotate(-60deg) translatex(70px); } #i2 #o3 { -webkit-transform: rotate(-90deg) translatex(70px); -moz-transform: rotate(-90deg) translatex(70px); -ms-transform: rotate(-90deg) translatex(70px); -o-transform: rotate(-90deg) translatex(70px); transform: rotate(-90deg) translatex(70px); } #i2 #o4 { -webkit-transform: rotate(-120deg) translatex(70px); -moz-transform: rotate(-120deg) translatex(70px); -ms-transform: rotate(-120deg) translatex(70px); -o-transform: rotate(-120deg) translatex(70px); transform: rotate(-120deg) translatex(70px); } #i2 #o5 { -webkit-transform: rotate(-150deg) translatex(70px); -moz-transform: rotate(-150deg) translatex(70px); -ms-transform: rotate(-150deg) translatex(70px); -o-transform: rotate(-150deg) translatex(70px); transform: rotate(-150deg) translatex(70px); } #i2 #o6 { -webkit-transform: rotate(-180deg) translatex(70px); -moz-transform: rotate(-180deg) translatex(70px); -ms-transform: rotate(-180deg) translatex(70px); -o-transform: rotate(-180deg) translatex(70px); transform: rotate(-180deg) translatex(70px); } #i2 #o7 { -webkit-transform: rotate(-210deg) translatex(70px); -moz-transform: rotate(-210deg) translatex(70px); -ms-transform: rotate(-210deg) translatex(70px); -o-transform: rotate(-210deg) translatex(70px); transform: rotate(-210deg) translatex(70px); } #i2 #o8 { -webkit-transform: rotate(-240deg) translatex(70px); -moz-transform: rotate(-240deg) translatex(70px); -ms-transform: rotate(-240deg) translatex(70px); -o-transform: rotate(-240deg) translatex(70px); transform: rotate(-240deg) translatex(70px); } #i2 #o9 { -webkit-transform: rotate(-270deg) translatex(70px); -moz-transform: rotate(-270deg) translatex(70px); -ms-transform: rotate(-270deg) translatex(70px); -o-transform: rotate(-270deg) translatex(70px); transform: rotate(-270deg) translatex(70px); } #i2 #o10 { -webkit-transform: rotate(-300deg) translatex(70px); -moz-transform: rotate(-300deg) translatex(70px); -ms-transform: rotate(-300deg) translatex(70px); -o-transform: rotate(-300deg) translatex(70px); transform: rotate(-300deg) translatex(70px); } #i2 #o11 { -webkit-transform: rotate(-330deg) translatex(70px); -moz-transform: rotate(-330deg) translatex(70px); -ms-transform: rotate(-330deg) translatex(70px); -o-transform: rotate(-330deg) translatex(70px); transform: rotate(-330deg) translatex(70px); } #i2 #o12 { -webkit-transform: rotate(0deg) translatex(70px); -moz-transform: rotate(0deg) translatex(70px); -ms-transform: rotate(0deg) translatex(70px); -o-transform: rotate(0deg) translatex(70px); transform: rotate(0deg) translatex(70px); } /* illusion 3 */ #i3 { color: #000000; font-family: times new roman; font-size: 250px; padding-left: 300px; } #i3 .rev { text-align: right; -webkit-transform: rotate(-180deg); -moz-transform: rotate(-180deg); -ms-transform: rotate(-180deg); -o-transform: rotate(-180deg); transform: rotate(-180deg); } /* illusion 4 */ #i4 .row { background-color: #fff; border-bottom: 5px solid #fff; height: 50px; -webkit-background-size: 60px 50px; -moz-background-size: 60px 50px; -ms-background-size: 60px 50px; -o-background-size: 60px 50px; background-size: 60px 50px; background-position: 0 50%; background-image: -webkit-linear-gradient(0deg, #000 90%, transparent 10%, transparent); background-image: -moz-linear-gradient(0deg, #000 90%, transparent 10%, transparent); background-image: -ms-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: -o-linear-gradient(0deg, #000 50%, transparent 50%, transparent); background-image: linear-gradient(0deg, #000 50%, transparent 50%, transparent); } /* illusion 5 */ @-webkit-keyframes custom_effect { 0% {opacity: 0;} 33% {opacity: 1;} 100% {opacity: 1;} } @-moz-keyframes custom_effect { 0% {opacity: 0;} 33% {opacity: 1;} 100% {opacity: 1;} } #i5 { background-color: #b2b2b2; height: 600px; margin: 0 auto; overflow: hidden; position: relative; width: 600px; } #i5 > div { float: left; height: 200px; padding-left: 200px; padding-top: 200px; position: relative; width: 200px; } #i5 div div { height: 50px; position: absolute; width: 50px; -webkit-border-radius: 50px; -moz-border-radius: 50px; -ms-border-radius: 50px; -o-border-radius: 50px; border-radius: 50px; background-color: #b2b2b2; background-image: -webkit-radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); background-image: -moz-radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); background-image: -o-radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); background-image: radial-gradient(50% 50%, circle, #fd19fd, #b2b2b2 70%); -moz-animation-name: custom_effect; -moz-animation-duration: 1.2s; -moz-animation-timing-function: linear; -moz-animation-iteration-count: infinite; -moz-animation-direction: normal; -moz-animation-delay: 0; -moz-animation-play-state: running; -moz-animation-fill-mode: forwards; -webkit-animation-name: custom_effect; -webkit-animation-duration: 1.2s; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: normal; -webkit-animation-delay: 0; -webkit-animation-play-state: running; -webkit-animation-fill-mode: forwards; } #i5 #o1 { -moz-transform: rotate(30deg) translatex(150px); -moz-animation-delay: 0.1s; -webkit-transform: rotate(30deg) translatex(150px); -webkit-animation-delay: 0.1s; } #i5 #o2 { -moz-transform: rotate(60deg) translatex(150px); -moz-animation-delay: 0.2s; -webkit-transform: rotate(60deg) translatex(150px); -webkit-animation-delay: 0.2s; } #i5 #o3 { -moz-transform: rotate(90deg) translatex(150px); -moz-animation-delay: 0.3s; -webkit-transform: rotate(90deg) translatex(150px); -webkit-animation-delay: 0.3s; } #i5 #o4 { -moz-transform: rotate(120deg) translatex(150px); -moz-animation-delay: 0.4s; -webkit-transform: rotate(120deg) translatex(150px); -webkit-animation-delay: 0.4s; } #i5 #o5 { -moz-transform: rotate(150deg) translatex(150px); -moz-animation-delay: 0.5s; -webkit-transform: rotate(150deg) translatex(150px); -webkit-animation-delay: 0.5s; } #i5 #o6 { -moz-transform: rotate(180deg) translatex(150px); -moz-animation-delay: 0.6s; -webkit-transform: rotate(180deg) translatex(150px); -webkit-animation-delay: 0.6s; } #i5 #o7 { -moz-transform: rotate(210deg) translatex(150px); -moz-animation-delay: 0.7s; -webkit-transform: rotate(210deg) translatex(150px); -webkit-animation-delay: 0.7s; } #i5 #o8 { -moz-transform: rotate(240deg) translatex(150px); -moz-animation-delay: 0.8s; -webkit-transform: rotate(240deg) translatex(150px); -webkit-animation-delay: 0.8s; } #i5 #o9 { -moz-transform: rotate(270deg) translatex(150px); -moz-animation-delay: 0.9s; -webkit-transform: rotate(270deg) translatex(150px); -webkit-animation-delay: 0.9s; } #i5 #o10 { -moz-transform: rotate(300deg) translatex(150px); -moz-animation-delay: 1.0s; -webkit-transform: rotate(300deg) translatex(150px); -webkit-animation-delay: 1.0s; } #i5 #o11 { -moz-transform: rotate(330deg) translatex(150px); -moz-animation-delay: 1.1s; -webkit-transform: rotate(330deg) translatex(150px); -webkit-animation-delay: 1.1s; } #i5 #o12 { -moz-transform: rotate(0deg) translatex(150px); -moz-animation-delay: 1.2s; -webkit-transform: rotate(0deg) translatex(150px); -webkit-animation-delay: 1.2s; } /* illusion 5 */ #i6 { background-color: #3f023e; height: 640px; margin: 0 auto; overflow: hidden; padding-left: 120px; position: relative; width: 900px; } #i6 .yellow { background-color: #b9bd04; background-image: -webkit-radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); background-image: -moz-radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); background-image: -o-radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); background-image: radial-gradient(50% 50%, circle, #fff531 40%, #b9bd04 80%); } #i6 .pink { background-color: #f101e8; background-image: -webkit-radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); background-image: -moz-radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); background-image: -o-radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); background-image: radial-gradient(50% 50%, circle, #0e0403 40%, #f101e8 80%); } #i6 > div { float: left; height: 320px; position: relative; width: 320px; } #i6 .r1 { height: 320px; position: absolute; width: 320px; -webkit-border-radius: 320px; -moz-border-radius: 320px; -ms-border-radius: 320px; -o-border-radius: 320px; border-radius: 320px; } #i6 .r2 { height: 240px; left: 40px; position: absolute; top: 40px; width: 240px; -webkit-border-radius: 240px; -moz-border-radius: 240px; -ms-border-radius: 240px; -o-border-radius: 240px; border-radius: 240px; } #i6 .r3 { height: 160px; left: 40px; position: absolute; top: 40px; width: 160px; -webkit-border-radius: 160px; -moz-border-radius: 160px; -ms-border-radius: 160px; -o-border-radius: 160px; border-radius: 160px; } #i6 .r4 { height: 80px; left: 40px; position: absolute; top: 40px; width: 80px; -webkit-border-radius: 80px; -moz-border-radius: 80px; -ms-border-radius: 80px; -o-border-radius: 80px; border-radius: 80px; } this is very big pack of styles, but i hope that this is ok. i have used several different css3 techniques: and keyframe animation, and transform rotate, and sometimes – gradients. live demo download in package conclusion hope you enjoyed the new demo. don’t forget to give thanks and leave a comment good luck! source: http://www.script-tutorials.com/css3-optical-illusions/
January 5, 2012
· 7,647 Views
article thumbnail
Create Your Own XML/JSON/HTML API with PHP
Develop your own API service for your PHP projects.
December 1, 2011
· 67,478 Views
article thumbnail
Click action Multi-level CSS3 Dropdown Menu
Nowadays, pure CSS3 menus are still very popular. Usually these are UL-LI based menus. Today we will continue making nice menus for you. This tip will create a multi-level dropdown menu, but today submenus will appear not with the onhover action, but with the onclick action instead. Here is what the final result will look like: Here are samples and downloadable packages: Live Demo download in package Ok, download the example files and lets start coding ! Step 1. HTML As usual, we start with the HTML. Here is the full html code with our menu. As you can see - this is multi-level menu. I hope that you can easily understand it. The whole menu is built on UL-LI elements. index.html Home Tutorials HTML / CSS JS / jQuery jQuery JS PHP MySQL XSLT Ajax Resources By category PHP MySQL Menu1 Menu1 Menu2 Menu3 Menu31 Menu32 Menu33 Menu34 Menu4 Ajax By tag name captcha gallery animation About Step 2. CSS Here are the CSS styles I used. First two selectors - a layout of our demo page. All rest belong to the menu. css/style.css /* demo page styles */ body { background:#eee; margin:0; padding:0; } .example { background:#fff url(../images/tech.jpg); width:770px; height:570px; border:1px #000 solid; margin:20px auto; padding:15px; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; } /* main menu styles */ #nav,#nav ul { background-image:url(../images/tr75.png); list-style:none; margin:0; padding:0; } #nav { height:41px; padding-left:5px; padding-top:5px; position:relative; z-index:2; } #nav ul { left:-9999px; position:absolute; top:37px; width:auto; } #nav ul ul { left:-9999px; position:absolute; top:0; width:auto; } #nav li { float:left; margin-right:5px; position:relative; } #nav li a { background:#c1c1bf; color:#000; display:block; float:left; font-size:16px; padding:8px 10px; text-decoration:none; } #nav > li > a { -moz-border-radius:6px; -webkit-border-radius:6px; -o-border-radius:6px; border-radius:6px; overflow:hidden; } #nav li a.fly { background:#c1c1bf url(../images/arrow.gif) no-repeat right center; padding-right:15px; } #nav ul li { margin:0; } #nav ul li a { width:120px; } #nav ul li a.fly { padding-right:10px; } /*hover styles*/ #nav li:hover > a { background-color:#858180; color:#fff; } /*focus styles*/ #nav li a:focus { outline-width:0; } /*popups*/ #nav li a:active + ul.dd,#nav li a:focus + ul.dd,#nav li ul.dd:hover { left:0; } #nav ul.dd li a:active + ul,#nav ul.dd li a:focus + ul,#nav ul.dd li ul:hover { left:140px; } Step 3. Images Our menu is using only three images: arrow.gif, tech.jpg and tr75.png. I didn't include them into tutorial because two of them are very small (will be difficult to locate) and the last one is just background image. All images will be in the package. Conclusion Hope you enjoyed this tutorial and learned something new. Good luck! From Script-tutorials
September 9, 2011
· 15,626 Views

Comments

Analog Clock with Pure CSS3 (without javascript)

Jan 10, 2012 · Sheikh Butt

Yes, possible, I took this image in web (this image was better and much clean than another clock faces)
How to create Animated 3D canvas object in HTML5

May 18, 2011 · Tayyab Ibrahim

scripts/html5logo.js var ctx = canvas.getContext('2d'); so this is math transformation of 2d into 3d it even have special made scripts/mathlib-min.js + scripts/k3d-min.js to make whole calculations more easy
How to create Animated 3D canvas object in HTML5

May 18, 2011 · Tayyab Ibrahim

http://www.kevs3d.co.uk/dev/html5logo/ is not 3D too, just illusion too (it have much More code to do it)
Data Validation – How to Validate Forums using HTML5

Apr 05, 2011 · Ayaz Malik

As for me - idea of form date validation at browser side is good. Need just prepare good proper HTML, and browser all will do by self (validate forms). Good.
Collection of Free Captcha’s for your Website

Feb 16, 2011 · Ayaz Malik

Thanks, if you have any another interesting themes which I can describe - just tell me
Collection of Free Captcha’s for your Website

Feb 14, 2011 · Ayaz Malik

Captcha always important

User has been successfully modified

Failed to modify user

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: