search
HomeWeb Front-endH5 TutorialSharing examples of using HTML5 Canvas to create keyboard and mouse animations_html5 tutorial skills

Keyboard controls the movement of the ball

As we all know, the animation we see is actually a series of rapid switching of static images, which gives the naked eye the visual effect of "moving images" due to visual afterimages. After understanding this, drawing animation effects on canvas becomes relatively simple. We only need to clear a certain static graphic first, and then redraw it at another location. Repeat this to make the static graphic move according to a certain trajectory to produce an animation effect.

Next, we draw a solid ball on the canvas, and then use the arrow keys on the keyboard to control the movement of the ball to produce dynamic effects. The sample code is as follows:

JavaScript CodeCopy content to clipboard
  1. "UTF-8">
  2. html5 canvas drawing movable ball entry example
  3. "moveBall(event)">
  4. "myCanvas" width="400px" height="300px" style="border: 1px solid red;">
  5. Your browser does not support the canvas tag.
  6. >
  7. //Get the Canvas object (canvas)
  8. var canvas = document.getElementById("myCanvas");
  9. //Represents the class of sphere
  10. function Ball(x, y ,radius, speed){
  11. this.x = x || 10; //The x coordinate of the sphere, the default is 10
  12. this.y = y || 10; //The y coordinate of the sphere, the default is 10
  13. this.radius = radius || 10; //The radius of the sphere, the default is 10
  14. this.speed = speed || 5; //The moving speed of the ball, the default is 5
  15.  
  16. //Move up
  17. this.moveUp = function(){
  18. this.y -= this.speed;
  19.  if(this.y
  20. //Prevent exceeding the upper boundary
  21.                                                                                                                                              
  22.                                                               
  23. };  
  24. //Move right
  25. this
  26. .moveRight =
  27. function
  28. (){
  29. this
  30. .x = this.speed;
  31. var
  32. maxX = canvas.width - this.radius;
  33. if
  34. (this.x > maxX){  
  35. //Prevent exceeding the right boundary
  36.  this.x = maxX; 
  37. }
  38. };
  39.  
  40. //Move left
  41. this.moveLeft = function(){
  42. this.x -= this.speed;
  43.  if(this.x
  44. //Prevent exceeding the left boundary
  45.  
  46. this
  47. .x = this.radius;                                                                
  48. };
  49.  
  50. //Move down
  51. this
  52. .moveDown =
  53. function(){ this
  54. .y =
  55. this.speed; var
  56. maxY = canvas.height -
  57. this.radius; if
  58. (
  59. this.y > maxY){ //Prevent exceeding the lower boundary
  60. this
  61. .y = maxY;
  62.                                                                };
  63. }
  64. //Draw the ball
  65. function drawBall(ball){
  66.  if(
  67. typeof
  68. ctx != "undefined"){ ctx.beginPath(); ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2,
  69. false
  70. );
  71. ctx.fill(); }
  72. }
  73. //Clear the canvas
  74. function clearCanvas(){
  75.  if(typeof ctx != "undefined"){
  76. ctx.clearRect(0, 0, 400, 300);
  77. }
  78. }
  79. var ball = new Ball();
  80. //Simply detect whether the current browser supports the Canvas object to avoid prompting syntax errors in some browsers that do not support html5
  81. if(canvas.getContext){ 
  82. //Get the corresponding CanvasRenderingContext2D object (brush)
  83. var ctx = canvas.getContext("2d");
  84. drawBall(ball);
  85. }
  86. //Callback handler function for onkeydown event
  87. //Control the movement of the ball according to the user’s keys
  88. function moveBall(event){
  89. switch(event.keyCode){
  90.  case 37: //Left arrow key  
  91. ball.moveLeft();
  92. break;
  93.  case 38: //Up direction key  
  94. ball.moveUp();
  95. break;
  96.  case 39: //Right arrow key  
  97. ball.moveRight();
  98. break;
  99. case 40: //Down arrow key
  100. ball.moveDown();
  101. break;
  102. default: //Other key operations do not respond
  103. return;
  104. }
  105.  
  106. clearCanvas(); //Clear the canvas first
  107. drawBall(ball); //Draw the latest ball
  108. }

Please use a browser that supports HTML5 to open the following web page to see the actual effect (use the arrow keys to move):
Use canvas to draw a movable ball.


Clown Smiley Face
You only need to understand a few APIs, and then use the required animation parameters to create this interesting web animation that can respond to your movements.
The first step is to draw the facial features

This clown has no ears and eyebrows, so only three organs are left, but we have to draw its two eyes separately, so there are four parts in total. Let’s take a look at the code first.

Code for drawing left eye

JavaScript CodeCopy content to clipboard
  1. var leftEye = new Kinetic.Line({
  2. x: 150,
  3. points: [0, 200, 50, 190, 100, 200, 50, 210],
  4. tension: 0.5,
  5. closed: true,
  6. stroke: 'white',
  7. strokeWidth: 10
  8. });

Code for drawing the right eye

JavaScript CodeCopy content to clipboard
  1. var rightEye = new Kinetic.Line({
  2. x: sw - 250,
  3. points: [0, 200, 50, 190, 100, 200, 50, 210],
  4. tension: 0.5,
  5. closed: true,
  6. stroke: 'white',
  7. strokeWidth: 10
  8. });

Code for drawing nose

JavaScript CodeCopy content to clipboard
  1. var nose = new Kinetic.Line({
  2. points: [240, 280, sw/2, 300, sw-240,280],
  3. tension: 0.5,
  4. closed: true,
  5. stroke: 'white',
  6. strokeWidth: 10
  7. });

Code for drawing mouth

JavaScript CodeCopy content to clipboard
  1. var mouth = new Kinetic.Line({
  2. points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],
  3. tension: 0.5,
  4. closed: true,
  5. stroke: 'red',
  6. strokeWidth: 10
  7. });

Would you feel disappointed? It turns out that it’s just a few lines of code. Yes, it’s that simple. I believe you are starting to feel confident that you can become a web game animation programmer!

Briefly explain the above code. Kinetic is the js toolkit we use. At the head of the page, we need to reference it like this:

JavaScript CodeCopy content to clipboard
  1. var mouth = new Kinetic.Line({
  2. points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],
  3. tension: 0.5,
  4. closed: true,
  5. stroke: 'red',
  6. strokeWidth: 10
  7. });

The others are several key points, line elasticity, color, width, etc. These are easy to understand.

The second step is to make the picture move

The reason why this animation is attractive is that it can respond to your mouse movements and interact with the user. This is the most critical aspect of a successful animation. If you observe carefully, the changes in the clown's facial features are just changes in shape. The eyes become larger, the mouth becomes larger, and the nose becomes larger. But the special thing is that this change is not an instant change, but a transitional one. There are some algorithms in it. This is the most worrying part. Fortunately, these algorithm technologies are very mature and do not require us to think about them. These animation engine libraries have encapsulated these technologies into very simple and convenient interfaces. Let’s take a look at how to get things moving.

Left eye animation

JavaScript CodeCopy content to clipboard
  1. var leftEyeTween = new Kinetic.Tween({
  2. node: leftEye,
  3. duration: 1,
  4. easing: Kinetic.Easings.ElasticEaseOut,
  5. y: -100,
  6. points: [0, 200, 50, 150, 100, 200, 50, 200]
  7. });

Right eye animation

JavaScript CodeCopy content to clipboard
  1. var rightEyeTween = new Kinetic.Tween({
  2. node: rightEye,
  3. duration: 1,
  4. easing: Kinetic.Easings.ElasticEaseOut,
  5. y: -100,
  6. points: [0, 200, 50, 150, 100, 200, 50, 200]
  7. });

Animation of nose

JavaScript CodeCopy content to clipboard
  1. var noseTween = new Kinetic.Tween({
  2. node: nose,
  3. duration: 1,
  4. easing: Kinetic.Easings.ElasticEaseOut,
  5. y: -100,
  6. points: [220, 280, sw/2, 200, sw-220,280]
  7. });

Mouth animation

JavaScript CodeCopy content to clipboard
  1. var mouthTween = new Kinetic.Tween({
  2. node: mouth,
  3. duration: 1,
  4. easing: Kinetic.Easings.ElasticEaseOut,
  5. points: [100, 250, sw/2, 250, sw - 100, 250, sw/2, sh-20]
  6. });

The code is very simple and the variable names are self-explanatory. It should not be difficult for programmers with a little experience to understand these codes. Basically every piece of code lets you provide some points to specify the decay mode and duration of the animation action.

Complete animation code

JavaScript CodeCopy content to clipboard
  1. nbsp;HTML>   
  2.   
  3.      
  4.     
  5.       body {   
  6.         margin: 0px;   
  7.         padding: 0px;   
  8.       }  
  9.       #container {   
  10.         background-color: black;   
  11.       }   
  12.        
  13.      
  14.      
  15.     
    "container">
      
  16.     <script><span class="string">"/js/lib/kinetic-v5.0.1.min.js"</script>>   
  17.     <script><span class="string">"defer"</script>>   
  18.       var sw = 578;   
  19.       var sh = 400;   
  20.       var stage = new Kinetic.Stage({   
  21.         container: 'container',   
  22.         width: 578,   
  23.         height: 400   
  24.       });   
  25.       var layer = new Kinetic.Layer({   
  26.         y: -30    
  27.       });   
  28.   
  29.       var leftEye = new Kinetic.Line({   
  30.         x: 150,   
  31.         points: [0, 200, 50, 190, 100, 200, 50, 210],   
  32.         tension: 0.5,   
  33.         closed: true,   
  34.         stroke: 'white',   
  35.         strokeWidth: 10        
  36.       });   
  37.   
  38.       var rightEye = new Kinetic.Line({   
  39.         x: sw - 250,   
  40.         points: [0, 200, 50, 190, 100, 200, 50, 210],   
  41.         tension: 0.5,   
  42.         closed: true,   
  43.         stroke: 'white',   
  44.         strokeWidth: 10      
  45.       });   
  46.   
  47.       var nose = new Kinetic.Line({   
  48.         points: [240, 280, sw/2, 300, sw-240,280],   
  49.         tension: 0.5,   
  50.         closed: true,   
  51.         stroke: 'white',   
  52.         strokeWidth: 10   
  53.       });   
  54.   
  55.       var mouth = new Kinetic.Line({   
  56.         points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],   
  57.         tension: 0.5,   
  58.         closed: true,   
  59.         stroke: 'red',   
  60.         strokeWidth: 10   
  61.       });   
  62.   
  63.       layer.add(leftEye)   
  64.            .add(rightEye)   
  65.            .add(nose)   
  66.            .add(mouth);   
  67.   
  68.       stage.add(layer);   
  69.   
  70.       // tweens   
  71.   
  72.       var leftEyeTween = new Kinetic.Tween({   
  73.         node: leftEye,   
  74.         duration: 1,   
  75.         easing: Kinetic.Easings.ElasticEaseOut,   
  76.         y: -100,   
  77.         points: [0, 200, 50, 150, 100, 200, 50, 200]   
  78.       });    
  79.   
  80.       var rightEyeTween = new Kinetic.Tween({   
  81.         node: rightEye,   
  82.         duration: 1,   
  83.         easing: Kinetic.Easings.ElasticEaseOut,   
  84.         y: -100,   
  85.         points: [0, 200, 50, 150, 100, 200, 50, 200]   
  86.       });   
  87.   
  88.       var noseTween = new Kinetic.Tween({   
  89.         node: nose,   
  90.         duration: 1,   
  91.         easing: Kinetic.Easings.ElasticEaseOut,   
  92.         y: -100,   
  93.         points: [220, 280, sw/2, 200, sw-220,280]   
  94.       });    
  95.   
  96.       var mouthTween = new Kinetic.Tween({   
  97.         node: mouth,   
  98.         duration: 1,   
  99.         easing: Kinetic.Easings.ElasticEaseOut,   
  100.         points: [100, 250, sw/2, 250, sw - 100, 250, sw/2, sh-20]   
  101.       });    
  102.   
  103.       stage.getContainer().addEventListener('mouseover'function() {   
  104.         leftEyeTween.play();   
  105.         rightEyeTween.play();   
  106.         noseTween.play();   
  107.         mouthTween.play();   
  108.       });   
  109.   
  110.       stage.getContainer().addEventListener('mouseout'function() {   
  111.         leftEyeTween.reverse();   
  112.         rightEyeTween.reverse();   
  113.         noseTween.reverse();   
  114.         mouthTween.reverse();   
  115.       });   
  116.   
  117.        
  118.      
  119.   

Watch the demo

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment