Canvas drawing animation effect

As we all know, the animation we see is actually a series of fast switching of static pictures, so that the naked eye produces the visual effect of "picture in motion" due to visual afterimages. After understanding this, it is relatively simple to draw animation effects on canvas. We only need to clear a static graphic first, and then redraw it at another position, and so on and so forth, let the static graphic move according to a certain trajectory, and then the animation effect can be generated.

 

Below, 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:

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>html5 canvas drawing movable ball entry example</title>
</head>
<body onkeydown="moveBall(event)">

<!-- Add canvas tag with red border for easy viewing on the page-->
<canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">
    Your browser does not support the canvas tag.
</canvas>

<script type="text/javascript">
    //Get the Canvas object (canvas)
    var canvas = document.getElementById("myCanvas");

    //Class representing the sphere
    function Ball(x, y ,radius, speed){
        this.x = x || 50; //The x coordinate of the sphere, the default is 10
        this.y = y || 50; //The y coordinate of the ball, the default is 10
        this.radius = radius || 50; //The radius of the ball, the default is 10
        this.speed = speed || 5; //The movement speed of the ball, the default is 5

        //Move up
        this.moveUp = function(){
            this.y -= this.speed;
            if(this.y < this.radius){
                // prevent exceeding the upper bound
                this.y = this.radius;
            }
        };

        //move to the right
        this.moveRight = function(){
            this.x += this.speed;
            var maxX = canvas.width - this.radius;
            if(this.x > maxX){
                // prevent going beyond the right border
                this.x = maxX;
//                alert("m")
            }
        };
        //move to the left
        this.moveLeft = function(){
            this.x -= this.speed;
            if(this.x < this.radius){
                // prevent going beyond the left border
                this.x = this.radius;
            }
        };

        //Move Downward
        this.moveDown = function(){
            this.y += this.speed;
            var maxY = canvas.height - this.radius;
            if(this.y > maxY){
                // prevent exceeding the lower bound
                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);
            //Create a CanvasGradient object representing the radioactive color gradient
            //The scope of this object is the annular area between the inner circle with (100,100) as the center and the radius of 10px and the outer circle with (100,100) as the center and the radius of 50px
            var canvasGradient = ctx.createRadialGradient(ball.x,ball.y,0,ball.x,ball.y,50);
            //Add a blue gradient at the position where the offset is 0 (that is, at the inner circle)
            canvasGradient.addColorStop(0,"blue");
            //Add a green gradient at the position where the offset is 0.5 (the middle position of the annular area radiating 50% from the inside to the outside)
            canvasGradient.addColorStop(0.5,"green");
            //Add a red gradient at the position where the offset is 0 (that is, at the outer circle)
            canvasGradient.addColorStop(1,"red");
            //Set the property value of fillStyle to the CanvasGradient object
            ctx.fillStyle = canvasGradient;
            ctx.fill();
        }
    }

    //Clear the canvas canvas
    function clearCanvas(){
        if(typeof ctx != "undefined"){
            ctx.clearRect(0, 0, 400, 300);
        }
    }

    var ball = new Ball ();
    //Simply detect whether the current browser supports Canvas objects, so as to avoid 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 for onkeydown event
    //Control the movement of the ball according to the user's key
    function moveBall(event){
        switch(event.keyCode){
            case 37: //Left arrow key
                ball.moveLeft();
                break;
            case 38: //up arrow 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(); //First clear the canvas
        drawBall(ball); //draw the latest ball
    }
</script>
</body>
</html>

 

 

 

 

expand:

①The key codes of the four direction keys are 37 (left), 38 (up), 39 (right) and 40 (down)

②The switch statement is used to perform different actions based on different conditions - syntax:

switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  n code that is not executed at the same time as case 1 and case 2
}

 

working principle:

① First set the expression n (usually a variable). The value of the expression is then compared to the value of each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent code from automatically running to the next case.

②default keyword, use the default keyword to specify what to do when the match does not exist

 

.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326226957&siteId=291194637