08 – Canvas(2) Informatics Department Parahyangan Catholic University.

Slides:



Advertisements
Similar presentations
Summer Computing Workshop. Introduction to Variables Variables are used in every aspect of programming. They are used to store data the programmer needs.
Advertisements

Using Bitmap graphics Having looked at vector graphics in the canvas, we will now look at using bitmap graphics.
Neal Stublen Why Use a Canvas?  Flexibility… Use of drawing primitives (lines, arcs, text) Direct access to element display pixels.
Programming Club IIT Kanpur
HTML 5 Previous version: HTML4.01, 1999 Still work in progress, most browsers support some of it.
Programming games More drawing. Text. Radian measure. Faces. Homework: Do your own drawings. Create index.html file. Upload work.
Mrs. Chapman. Tabs (Block Categories) Commands Available to use Script Area where you type your code Sprite Stage All sprites in this project.
1 Flash Actionscript Animation. 2 Introduction to Sprites We will now look at implementing Sprites in Flash. We should know enough after this to create.
Information Technology Center Hany Abdelwahab Computer Specialist.
Mr. Wortzman. Tabs (Block Categories) Available Blocks Script Area Sprite Stage All sprites in this project.
CHAPTER 21 INTRODUCING THE HTML 5 CANVAS. LEARNING OBJECTIVES How to create a canvas using the and tag pair How to test if a browser supports canvas operations.
Canvas, SVG, Workers Doncho Minkov Telerik Corporation
2 What is pyGame? A set of Python modules to make it easier to write games. –home page: –documentation:
Programming Games Computer science big ideas. Computer Science jargon. Show virtual dog Homework: [Catch up: dice game, credit card or other form.] Plan.
Copyright 2007, Information Builders. Slide 1 Maintain & JavaScript: Two Great Tools that Work Great Together Mark Derwin and Mark Rawls Information Builders.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
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.
Locally Edited Animations We will need 3 files to help get us started at
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
JavaScript Informatics for economists I. Introduction Programming language used in web pages. Simple and easy to use – written in HTML document. Client.
Enhancing JavaScript Using Application Programming Interfaces (APIs)
BIM211 – Visual Programming Objects, Collections, and Events 1.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
Getting Started with Canvas IDIA Spring 2013 Bridget M. Blodgett.
HTML 5 Tutorial Chapter 5 Canvas. Canvas The tag is used to display graphics. The Canvas is a rectangular area we control each and every pixel of it.
HTML5 CANVAS. SAVING INFORMATION BETWEEN FUNCTION CALLS.
Session: 17. © Aptech Ltd. 2Canvas and JavaScript / Session 17  Describe Canvas in HTML5  Explain the procedure to draw lines  Explain the procedure.
Element. The element Used to dynamically draw graphics using javascript. Capable of drawing paths, circles, rectangles, text, and images.
Programming Games Show project. Refresher on coordinates. Scaling, translation. HTML5 logo. Refresher on animation. Bouncing ball. Homework: Do your own.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
Programming games Flash drawing trick(s). Past due: Your completion of rock-paper-scissors) Classwork: Bouncing ball: read tutorial. Start coding.
Programming games Show your version of Bo the dog. Start cannonball Preview: video, audio work session (cannonball) Homework: Cannonball with ball in a.
CS 174: Web Programming October 7 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Programming for Artists ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 10 Fall 2010.
Learning Unity. Getting Unity
Creating HUD Rings. Step 1 Open a new document in Illustrator. You can set it to the size you prefer to work in. In my case I have it set at 500px by.
Programming Games Reprise on drawing on canvas. Jargon (concepts): objects. Demonstrate slingshot. Mouse events. Work on your cannonball. Homework: Finish.
CS 174: Web Programming October 5 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Variables. Todays Lesson  In todays lesson you are going to:  Learn to use variables  Learn to ask for user input  Learn to save the users response.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 21 - “Cat and Mouse” Painter Application.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
Programming games Context of what we are doing. Drawing on canvas. Homework: [Complete coin toss examples.] Do your own drawings. Upload files to website.
Programming games Review concepts. Crooked coin toss. Drawing on canvas. Homework: Complete [static] drawings. Upload files to website.
G RAPHICS & I NTERACTIVE P ROGRAMMING Lecture 2 More Programming with Processing.
Tutorial 7 Creating Animations. XP Objectives Learn about animation Create a timeline Add AP divs and graphics to a timeline Move and resize animation.
Introduction to JavaScript CSc 2320 Fall 2014 Disclaimer: All words, pictures are adopted from “Simple JavaScript”by Kevin Yank and Cameron Adams and also.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
Animating the Canvas Animation is achieved with the following: 1.Clear the area that is changing context.clearRect(x, y, width, height); 2.Save the canvas.
School of Computing and Information Systems RIA Animation, part I.
Pemrograman Berbasis Web
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
XP Tutorial 3 Creating Animations. XP New Perspectives on Macromedia Flash MX Elements of Animation Layers are used to organize the content of.
Create a camera using basic shapes only. Using the eye dropper to specify a color  Open camera.ai  use the eye dropper tool and click the first swatch.
07 – HTML5 Canvas (1) Informatics Department Parahyangan Catholic University.
Graphics in Python On entry: Run Python 2.78 from N: drive/computing and ICT VLE: Computing home page - check your feedback Success criteria: ●Understands.
That Gauge is COOL! 
What is a Function Expression?
MOM! Phineas and Ferb are … Aims:
Internet of the Past.
Scratch for Interactivity

ISC440: Web Programming II Ch14: HTML5 Canvas
The Canvas.
Updating an Animated Scene
Drawing Graphics in JavaScript
CSc 337 Lecture 21: Canvas.
Web Programming and Design
JavaScript – Let’s Draw!
CSc 337 Lecture 19: Canvas.
Presentation transcript:

08 – Canvas(2) Informatics Department Parahyangan Catholic University

 Previously, we’ve learned how to change drawing style (eg. fillStyle, strokeStyle)  A canvas’ drawing state is its condition at a point of time. This includes various of canvas’ properties (color, alpha, transformation, etc.)

 We can store a canvas’ drawing state and restore it later  Example: context.fillStyle = “red"; context.fillRect(50, 50, 100, 100); // Red square context.save(); // Save the canvas state context.fillStyle = “blue"; context.fillRect(200, 50, 100, 100); // Blue square context.restore(); // Restore the canvas state context.fillRect(350, 50, 100, 100); // Red square

 We can save multiple states  They are stored in a stack  Meaning that the last saved state will be restored first (LIFO)  This is useful when we need to change the canvas’ styles inside a function. We want to restore the previous styles before exiting the function (example later)

 Animating in canvas is really no different from animating in general  animation is just a bunch of images, each slightly different, that are displayed in succession at incredible speed  The trick is to show enough images per second to trick the human eye into thinking that what it sees is a moving object

 Example: Source: Source:

 In HTML, we only have one canvas  Animation done by repeating these 3 steps rapidly:  Draw  Clear  Update

 Example: var canvas = $("#myCanvas"); var context = canvas.get(0).getContext("2d"); var canvasWidth = canvas.width(); var canvasHeight = canvas.height(); function animate() { setTimeout(animate, 33); }; animate();//first call to animate() function why 33 ?

 Suppose we don’t want the animation to run forever, we can use one boolean variable to indicate when the animation should run. This variable can be toggled with simple Java Script dan HTML buttons  Example: var playAnimation = true; … if (playAnimation) { setTimeout(animate, 33); };

 Moving a rectangle var x = 0; function animate() { x++; context.clearRect(0, 0, canvasWidth, canvasHeight); context.fillRect(x, 250, 10, 10); setTimeout(animate, 33); }; UPDATE CLEAR DRAW

 The wrong way: var firstX = 0; var secondX = 50; var thirdX = 100; function animate() { firstX++; secondX++; thirdX++; context.clearRect(0, 0, canvasWidth, canvasHeight); context.fillRect(firstX, 50, 10, 10); context.fillRect(secondX, 100, 10, 10); context.fillRect(thirdX, 150, 10, 10); setTimeout(animate, 33); };

 The right way: use object template (class) var Shape = function(x, y) { this.x = x; this.y = y; }; var shapes = new Array(); shapes.push(new Shape(50, 50)); shapes.push(new Shape(100, 100)); shapes.push(new Shape(150, 150));

 The right way: use object template (class) function animate() { context.clearRect(0, 0, canvasWidth, canvasHeight); for (var i = 0; i < shapes.length; i++) { shapes[i].x++; context.fillRect(shapes[i].x, shapes[i].y, 10, 10); } setTimeout(animate, 33); };

 Integrating update and draw method to the class var Rectangle = function(x, y) { this.x = x; this.y = y; this.draw = function(contex){ context.fillRect(this.x, this.y, 10, 10); } this.update = function(){ this.x++; }

 We can do “polymorphism” in JS function Rectangle(x,y,width,height, color){ this.x = x; this.y = y; this.width = width; this.height = height; this.color = color; this.draw = function(context){ context.save(); context.fillStyle = color; context.fillRect(x, y, width, height); context.restore(); } this.move = function(){ x++; }

 We can do “polymorphism” in JS function Circle(x,y,radius, color){ this.x = x; this.y = y; this.radius = radius; this.color = color; this.draw = function(context){ context.save(); context.fillStyle = color; context.beginPath(); context.arc(x, y, radius, 0, Math.PI*2, false); context.closePath(); context.fill(); context.restore(); } this.move = function(){ x++;y++; } }

 We can do “polymorphism” in JS var shapes = Array(); shapes.push(new Rectangle(10,10,10,10,"red")); shapes.push(new Rectangle(10, 30, 10, 10, "blue")) shapes.push(new Circle(10, 50, 15, "green")); function animate(){ context.clearRect(0, 0, canvasWidth, canvasHeight); for(var i=0; i<shapes.length; i++){ shapes[i].draw(context); shapes[i].move(); } setTimeout(animate, 33); }

Thus:  sin(  ) = y / dist y = sin(  ) * dist  cos(  ) = x / dist x = cos(  ) * dist x y  dist Recall: In Java Script, use Math.sin(radian) and Math.cos(radian). Don’t forget to use radian angle

 Example function Circle(color){ this.x = Math.random() * canvasWidth; this.y = Math.random() * canvasHeight; this.radius = 10 + Math.random() * 30; this.color = color; this.angle = Math.random()*(2*Math.PI); this.speed = 5+Math.random()*5;... this.move = function(){ this.x += Math.cos(this.angle)*this.speed; this.y += Math.sin(this.angle)*this.speed; } these values are constant, thus can be precomputed

 When a shape reaches the edge of the canvas, we might want it to bounce, instead of disappearing

 Add two variable as an x direction modifier and y direction modifier x y  dist -x -y

 Add two variable as an x direction modifier and y direction modifier Example1 in HTML page… //0..90 degree (x positive, y positive) this.angle = Math.random()*(0.5*Math.PI); this.dirX = Math.random()<0.5?1:-1;//randomize x direction this.dirY = Math.random()<0.5?1:-1;//randomize y direction this.deltaX = Math.cos(this.angle)*this.speed; this.deltaY = Math.sin(this.angle)*this.speed; this.move = function(){ this.x += this.deltaX * this.dirX; this.y += this.deltaY * this.dirY; if(this.x canvasWidth)this.dirX *= -1; if(this.y canvasHeight)this.dirY *= -1; }

 In previous code, we detect whether the circle’s center coordinate has passed the boundary radius We want to bounce when the circle hits the boundary

 Includes the circle’s radius in the calculation this.move = function(){ this.x += this.deltaX * this.dirX; this.y += this.deltaY * this.dirY; if(this.x - this.radius < 0) this.dirX = 1; if(this.x + this.radius > canvasWidth) this.dirX = -1; if(this.y - this.radius < 0) this.dirY = 1; if(this.y + this.radius > canvasHeight) this.dirY = -1; } Example2 in HTML page…

 Suppose we want to change the speed of the animation when the user click on the canvas  Add a modifier variable that ranged 0..4  Add an onclick event  Move formula is now booster = 0; canvas.get(0).onclick = function(){ booster = (booster+1)%5; }; this.x += this.deltaX*this.dirX * (1+booster); this.y += this.deltaY*this.dirY * (1+booster);

 addEventListener works similarly, but you can attach more than one function to a single event  Example: canvas.get(0).addEventListener("click", function(){ booster = (booster+1)%5; }); canvas.get(0).addEventListener("click", function(){ console.log(booster); }); Example3 in HTML page…

 A canvas, by default, cannot be focused, so it cannot receive a keydown event  One way around is to attach the keydown event to the browser’s window  Example window.addEventListener("keydown", function(e){ if(e.keyCode == 38)// up key booster += 0.2; else if(e.keyCode == 40)//down key booster -= 0.2; if(booster < 0)booster = 0; }); variable containing the event’s properties, such as what object is trigered the event, what key is pressed, etc. Example4 in HTML page…

 We can draw an image using the drawImage() method  However, drawing an unloaded image will throw a DOM error, so we have to check whether the image is ready to be drawn  Example: // Background image var bgReady = false; var bgImage = new Image(); bgImage.onload = function () { bgReady = true; }; bgImage.src = "wood.png";

 On animate() function: function animate(){ context.clearRect(0, 0, canvasWidth, canvasHeight); if(bgReady) context.drawImage(bgImage, 0, 0); for(var i=0; i<shapes.length; i++){ shapes[i].draw(context); shapes[i].move(); } setTimeout(animate, 33); } Example5 in HTML page…

 Shapes & Images are drawn on a canvas in layer-by- layer manner. The first image drawn is the bottom most layer, and so on.  Thus this is a wrong order: for(var i=0; i<shapes.length; i++){ shapes[i].draw(context); shapes[i].move(); } if(bgReady) context.drawImage(bgImage, 0, 0);

 Game animation is slightly more complicated, because it reacts to user’s input, instead of just a matter of fps.  Since game design is out of this course’s scope, those whose interested can search for tutorials on the web

 One good introductory tutorial by Matt Hackett html5-canvas-game/ html5-canvas-game/