


Sharing 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:
- "UTF-8">
-
html5 canvas drawing movable ball entry example - "moveBall(event)">
- Your browser does not support the canvas tag.
- >
- //Get the Canvas object (canvas)
- var canvas = document.getElementById("myCanvas");
- //Represents the class of sphere
- function Ball(x, y ,radius, speed){
- this.x = x || 10; //The x coordinate of the sphere, the default is 10
- this.y = y || 10; //The y coordinate of the sphere, the default is 10
- this.radius = radius || 10; //The radius of the sphere, the default is 10
- this.speed = speed || 5; //The moving speed of the ball, the default is 5
- //Move up
- this.moveUp = function(){
- this.y -= this.speed;
- if(this.y //Prevent exceeding the upper boundary
- }; //Move right
- this
- .moveRight = function
- (){ this
- .x = this.speed; var
- maxX = canvas.width - this.radius; if
- (this.x > maxX){ //Prevent exceeding the right boundary
- this.x = maxX;
- }
- };
- //Move left
- this.moveLeft = function(){
- this.x -= this.speed;
- if(this.x //Prevent exceeding the left boundary
- this
- .x = this.radius; };
- //Move down
- this .moveDown =
- function(){ this .y =
- this.speed; var maxY = canvas.height -
- this.radius; if (
- this.y > maxY){ //Prevent exceeding the lower boundary
- this .y = maxY;
- };
- }
- //Draw the ball
- function drawBall(ball){
- if( typeof
- ctx != "undefined"){ ctx.beginPath(); ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2, false
- );
- ctx.fill(); }
- }
- //Clear the canvas
- function clearCanvas(){
- if(typeof ctx != "undefined"){
- ctx.clearRect(0, 0, 400, 300);
- }
- }
- var ball = new Ball();
- //Simply detect whether the current browser supports the Canvas object to avoid prompting syntax errors in some browsers that do not support html5
- if(canvas.getContext){
- //Get the corresponding CanvasRenderingContext2D object (brush)
- var ctx = canvas.getContext("2d");
- drawBall(ball);
- }
- //Callback handler function for onkeydown event
- //Control the movement of the ball according to the user’s keys
- function moveBall(event){
- switch(event.keyCode){
- case 37: //Left arrow key
- ball.moveLeft();
- break;
- case 38: //Up direction key
- ball.moveUp();
- break;
- case 39: //Right arrow key
- ball.moveRight();
- break;
- case 40: //Down arrow key
- ball.moveDown();
- break;
- default: //Other key operations do not respond
- return;
- }
- clearCanvas(); //Clear the canvas first
- drawBall(ball); //Draw the latest ball
- }
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
- var leftEye = new Kinetic.Line({
- x: 150,
- points: [0, 200, 50, 190, 100, 200, 50, 210],
- tension: 0.5,
- closed: true,
- stroke: 'white',
- strokeWidth: 10
- });
Code for drawing the right eye
- var rightEye = new Kinetic.Line({
- x: sw - 250,
- points: [0, 200, 50, 190, 100, 200, 50, 210],
- tension: 0.5,
- closed: true,
- stroke: 'white',
- strokeWidth: 10
- });
Code for drawing nose
- var nose = new Kinetic.Line({
- points: [240, 280, sw/2, 300, sw-240,280],
- tension: 0.5,
- closed: true,
- stroke: 'white',
- strokeWidth: 10
- });
Code for drawing mouth
- var mouth = new Kinetic.Line({
- points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],
- tension: 0.5,
- closed: true,
- stroke: 'red',
- strokeWidth: 10
- });
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:
- var mouth = new Kinetic.Line({
- points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],
- tension: 0.5,
- closed: true,
- stroke: 'red',
- strokeWidth: 10
- });
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
- var leftEyeTween = new Kinetic.Tween({
- node: leftEye,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- y: -100,
- points: [0, 200, 50, 150, 100, 200, 50, 200]
- });
Right eye animation
- var rightEyeTween = new Kinetic.Tween({
- node: rightEye,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- y: -100,
- points: [0, 200, 50, 150, 100, 200, 50, 200]
- });
Animation of nose
- var noseTween = new Kinetic.Tween({
- node: nose,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- y: -100,
- points: [220, 280, sw/2, 200, sw-220,280]
- });
Mouth animation
- var mouthTween = new Kinetic.Tween({
- node: mouth,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- points: [100, 250, sw/2, 250, sw - 100, 250, sw/2, sh-20]
- });
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
- nbsp;HTML>
- body {
- margin: 0px;
- padding: 0px;
- }
- #container {
- background-color: black;
- }
-
"container">
- <script><span class="string">"/js/lib/kinetic-v5.0.1.min.js"</script>>
- <script><span class="string">"defer"</script>>
- var sw = 578;
- var sh = 400;
- var stage = new Kinetic.Stage({
- container: 'container',
- width: 578,
- height: 400
- });
- var layer = new Kinetic.Layer({
- y: -30
- });
- var leftEye = new Kinetic.Line({
- x: 150,
- points: [0, 200, 50, 190, 100, 200, 50, 210],
- tension: 0.5,
- closed: true,
- stroke: 'white',
- strokeWidth: 10
- });
- var rightEye = new Kinetic.Line({
- x: sw - 250,
- points: [0, 200, 50, 190, 100, 200, 50, 210],
- tension: 0.5,
- closed: true,
- stroke: 'white',
- strokeWidth: 10
- });
- var nose = new Kinetic.Line({
- points: [240, 280, sw/2, 300, sw-240,280],
- tension: 0.5,
- closed: true,
- stroke: 'white',
- strokeWidth: 10
- });
- var mouth = new Kinetic.Line({
- points: [150, 340, sw/2, 380, sw - 150, 340, sw/2, sh],
- tension: 0.5,
- closed: true,
- stroke: 'red',
- strokeWidth: 10
- });
- layer.add(leftEye)
- .add(rightEye)
- .add(nose)
- .add(mouth);
- stage.add(layer);
- // tweens
- var leftEyeTween = new Kinetic.Tween({
- node: leftEye,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- y: -100,
- points: [0, 200, 50, 150, 100, 200, 50, 200]
- });
- var rightEyeTween = new Kinetic.Tween({
- node: rightEye,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- y: -100,
- points: [0, 200, 50, 150, 100, 200, 50, 200]
- });
- var noseTween = new Kinetic.Tween({
- node: nose,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- y: -100,
- points: [220, 280, sw/2, 200, sw-220,280]
- });
- var mouthTween = new Kinetic.Tween({
- node: mouth,
- duration: 1,
- easing: Kinetic.Easings.ElasticEaseOut,
- points: [100, 250, sw/2, 250, sw - 100, 250, sw/2, sh-20]
- });
- stage.getContainer().addEventListener('mouseover', function() {
- leftEyeTween.play();
- rightEyeTween.play();
- noseTween.play();
- mouthTween.play();
- });
- stage.getContainer().addEventListener('mouseout', function() {
- leftEyeTween.reverse();
- rightEyeTween.reverse();
- noseTween.reverse();
- mouthTween.reverse();
- });

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.

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.

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.

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 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.

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment