Game Development with JS and Canvas 2D

Slides:



Advertisements
Similar presentations
Working with images and scenes CS 5010 Program Design Paradigms “Bootcamp” Lesson 2.5 TexPoint fonts used in EMF. Read the TexPoint manual before you delete.
Advertisements

Programming games More drawing. Text. Radian measure. Faces. Homework: Do your own drawings. Create index.html file. Upload work.
CANVAS Fundamentals. What is Canvas? Canvas is a medium for oil painting. One of the earliest oils on canvas is a French Madonna from Canvas is.
HTML, HTML5 Canvas, JavaScript PART 3 LOOKING MORE CLOSELY AT FULL BLOWN GAME DESIGN A PATTERNED BACKGROUND (CREATED WTIH LOOPS) WITH A MOVING OBJECT CHALLENGES.
Element. The element Used to dynamically draw graphics using javascript. Capable of drawing paths, circles, rectangles, text, and images.
CS 174: Web Programming October 5 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Creating Graphics for the Web Learning & Development Team Telerik Software Academy.
Intro to the Canvas Canvas is an HTML5 element If you see this, your browser doesn't support the canvas Canvas is manipulated with javascript c = document.getElementById("mycanvas");
HTML – Other Tags Semantic Tags, Frames, Embed Multimedia Content, Others SoftUni Team Technical Trainers Software University
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Programming games Review concepts. Crooked coin toss. Drawing on canvas. Homework: Complete [static] drawings. Upload files to website.
CSS Transitions and Animations Animated HTML Elements SoftUni Team Technical Trainers Software University
School of Computing and Information Systems RIA Animation, part I.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Lab 5: More on Events and Introduction to the Canvas Tag User Interface Lab: GUI Lab Sep. 23 rd, 2013.
07 – HTML5 Canvas (1) Informatics Department Parahyangan Catholic University.
That Gauge is COOL! 
Databases basics Course Introduction SoftUni Team Databases basics
Classes and Class Members
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
Build a WordPress Site A Real Life Example: Create a Fully Functional WP Business Web Site from Scratch Building a WP Site SoftUni Team Technical Trainers.
What is a Function Expression?
ASP.NET Integration Testing
Parsing JSON JSON.NET, LINQ-to-JSON
State Management Cookies, Sessions SoftUni Team State Management
Browser Routing Design Patterns in JS
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
Entity Framework: Code First
C#/Java Web Development Basics
MVC Architecture. Routing
Creating React Components with JSX and Babel
Front-End Framework for Responsive Web Sites
Entity Framework: Relations
CMPE 280 Web UI Design and Development September 12 Class Meeting
The Right Way Control Flow
Classes and Class Members
MVC Architecture, Symfony Framework for PHP Web Apps
AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.
Canvas Notes
C# Web Development Basics
Creating UI elements with Handlebars
Web Fundamentals (HTML and CSS)
Extending functionality using Collections
ASP.NET Filters SoftUni Team ASP.NET MVC Introduction
Making big SPA applications
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Course Overview, Trainers, Evaluation
Scheduled Tasks and Web Socket
CSS Transitions and Animations
Train the Trainers Course
Directives & Forms Capturing User Input SoftUni Team
JavaScript: ExpressJS Overview
CSS Transitions and Animations
Iterators and Generators
РОСІЙСЬКА МОВА Кількість завдань - 51 Час на виконання – 150 хв.
ФІЗИКА Кількість завдань - 34 Час на виконання – 180 хв.
ISC440: Web Programming II Ch14: HTML5 Canvas
The Canvas.
Sample heading First line of text Second line of text
سرطان پستان دکتر مریم طباطباییان پاییز ۱۳۹۱
Graphics Canvas.
CSc 337 Lecture 20: Canvas.
Working with images and scenes
JavaScript – Let’s Draw!
Presentation transcript:

Game Development with JS and Canvas 2D Simple Game Development with JS, Canvas 2D, DOM and Events Canvas 2D SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents Intro to Canvas 2D Draw Figures, Text and Images Simple Animations with Canvas Handle Keyboard / Mouse Events Creating a Game with Canvas Animation – Step by Step The Game Loop, Animation, Collision Detection, Game Controls

Have a Question? sli.do #JSCORE

Introduction to Canvas 2D Drawing Simple Figures

HTML5 Canvas API A canvas is used to draw graphics inside a browser, using JS Supports 2D and hardware-accelerated 3D via WebGL Examples: http://processingjs.org/ http://fabricjs.com/ https://playcanvas.com/play Before HTML5, Flash was used for web graphics

<canvas width="800" height="600" id="canvas"></canvas> HTML5 Canvas API (2) Defined in HTML via the <canvas> tag: Controlled with JavaScript via its context object: Size of the canvas, defined in pixels Used by JavaScript for identification <canvas width="800" height="600" id="canvas"></canvas> let canvas = document.getElementById("canvas"); let ctx = canvas.getContext("2d“);

Drawing Shapes The API offers built-in functions for drawing simple shapes Simplest shape is a rectangle Drawing parameters (color, linewidth) can be customized Top-left corner Dimensions ctx.fillRect(x, y, width, height)

Canvas Coordinates Coordinates (0; 0) at top-left

Example: Draw Checkerboard for (let row = 0; row < 8; row++) { for (let col = 0; col < 8; col++) { if ((row + col) % 2 == 0) { let x = 25 + col * 50; let y = 25 + row * 50; ctx.fillRect(x, y, 50, 50); }

Drawing Shapes (2) Lines and paths can be drawn with similar commands ctx.beginPath(); // Start new shape ctx.moveTo(x, y); // Move cursor ctx.lineTo(x, y); // Draw line ctx.closePath(); // Draw line to start ctx.stroke(); // Apply outline ctx.fill(); // Fill shape

Example: Draw Figure Draw triangle ctx.beginPath(); ctx.moveTo(10,50); ctx.lineTo(50,10); ctx.lineTo(50,90); ctx.fill();

Example: Draw Figure (2) Draw smiley face ctx.beginPath(); ctx.arc(75,75,50,0,Math.PI*2,true); ctx.moveTo(110,75); ctx.arc(75,75,35,0,Math.PI,false); ctx.moveTo(65,65); ctx.arc(60,65,5,0,Math.PI*2,true); ctx.moveTo(95,65); ctx.arc(90,65,5,0,Math.PI*2,true); ctx.stroke();

Using Colors And Patterns The color and pattern of default shapes can be customized Shape fill can be changed using ctx.fillStyle Line color can be changed using ctx.strokeStyle Valid formats are Color string literals: 'black', 'red', 'orange', etc. CSS Color: '#FFA500' RGBA combination: 'rgba(255, 165, 0, 1)'

Line strokes can be further customized Line Styles Line strokes can be further customized lineWidth – changes width of line lineCap – changes style of line ends lineJoin – changes appearance of corners setLineDash(segments) – changes the dash pattern Dash patterns are defined as an array of lengths for alternating solid and gap segments

Live Demo Shapes and Styles

Draws whole image using original dimensions Images You can draw images on the canvas Not all parameters are needed Image resource Source coordinates ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); Target coordinates Draws whole image using original dimensions ctx.drawImage(image, dx, dy);

Destination coordinates Images (2) Source coordinates Cropping an image Destination coordinates

Drawing Text Text can be outlined or filled, similar to other shapes And customized: ctx.font – changes the font type and size ctx.textAlign – changes text alignment ctx.fillText(text, x, y); ctx.strokeText(text, x, y);

Example: Draw Button Draw a button with a label Draw button base ctx.fillStyle = 'orange'; ctx.fillRect(30, 30, 200, 40); ctx.fillStyle = 'white'; ctx.font = "24px monospace"; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText("Submit", 130, 50);

Problem: Rounded Button Draw a button with a label and rounded edges

Animation with Canvas 2D Creating Simple Animations

Animation Basics Animation is achieved by gradually changing the contents of the canvas to smoothly morph it from one state to another Most often, by changing the objects’ position 10 20 30 40 50

Animation Basics (2) Timing (automatic redraw) is handled by the browser setInterval(func, t) – execute every t milliseconds requestAnimationFrame(func) – execute before the next frame draw Example: loading bar

Animation Basics (3) Clearing the canvas removes the previous frame This allows movement to be simulated We can clear the entire canvas or just parts of it Example: Bouncing ball ctx.clearRect(x, y, width, height);

User Interaction with Keyboard / Mouse Handling Events User Interaction with Keyboard / Mouse

Browser Events Events are signals, sent from various sources Buttons, keyboard presses, mouse movement/clicks The browser can “listen” for events A listener can be attached to any HTML object The specified function is executed whenever an event of the correct type is registered target.addEventListener(type, func);

Example: Animate on Button Press HTML JavaScript <button type="button" id="drawBtn">Draw</button> let btn = document.getElementById('drawBtn'); btn.addEventListener('click', animate); function animate() {…}

Event Handler The event handler function can take one parameter The parameter holds information about the event Useful when working with keyboard and mouse events function handler(event) { // Do stuff }

Keyboard Events keydown, keypress, keyup – detect keyboard event event.code – string representation the key Example: Move object with keyboard function handler(event) { if (event.code == "ArrowLeft") { position.x--; } else if (event.code == "ArrowRight") { position.x++; } }

Mouse Events click, mousemove – detect mouse events event.button – button pressed event.clientX, event.clientY – coordinates Example: Shoot ball towards mouse location function handler(event) { ball.x = 0; // Move ball to left edge ball.y = event.clientY; animate(); // Start animation }

Game Loop Tie It All Together

The Main Game Loop Initialize Check game state Record button presses, mouse state Process movement, physics, AI, etc. Render Cleanup

Sample Implementation Define loop function main() { update(); render(); requestAnimationFrame(main); } function update() {…} function render() {…} Main procedures Start loop

Creating a Game with Canvas 2D Live Demo Creating a Game with Canvas 2D

Summary Canvas API Basics Simple Animation Game Programming Patterns

Game Development with JS and Canvas 2D https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.