Simple uniform line animation

Canvas animation is still inseparable from js timer mechanism

There are two main types of JS timers

  • 1. SetInterval (WHICH I won’t cover)
  • 2.window.requestAnimationFrame

Window. RequestAnimationFrame (recommended)

Tell the browser that you want to perform an animation and ask the browser to call the specified callback function to update the animation before the next redraw. This method needs to be passed a callback function as an argument, which will be executed before the next browser redraw. You should call this method when you are ready to update the animation. This will cause the browser to call the animation function you passed to the method (that is, your callback function) before the next redraw. Callback execution is typically 60 times per second, but in most browsers that follow W3C recommendations, the number of callback executions usually matches the number of browser screen refreshes. To improve performance and battery life, requestAnimationFrame() is suspended in most browsers when the requestAnimationFrame() is running in a background TAB or hidden to improve performance and battery life.

sample

Quoted from MDN developer.mozilla.org/zh-CN/docs/…

const element = document.getElementById('some-element-you-want-to-animate');
let start;

function step(timestamp) {
  if (start === undefined)
    start = timestamp;
  const elapsed = timestamp - start;

  // Here, 'math.min ()' is used to ensure that the element stops at just 200px.
  element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';

  if (elapsed < 2000) { // Stop animation after two seconds
    window.requestAnimationFrame(step); }}window.requestAnimationFrame(step);
Copy the code

Do a ball of uniform motion

<canvas id="tutorial" width="1260px" height="800px" ref="canvas" style="border: 1px solid #999;" ></canvas>

Initialize canvas (using vUE syntax) // Get canvas element this.canvas = document.getelementByID (‘tutorial’) // Get draw two-dimensional context this.ctx = this.canvas.getContext(‘2d’)

Use canvas to draw a small ball

        // vx represents the left side of horizontal x
        initcanvascircle(vx) {
            this.ctx.fillStyle = '#EEEEEE'
            this.ctx.fillRect(0.0.1260.800)
            this.ctx.strokeStyle = '# 000000'
            this.ctx.strokeRect(1.1.1258.798)
            // Start drawing the graph
            this.ctx.beginPath()
            this.ctx.fillStyle = 'HotPink'
            this.ctx.arc(vx, 100.30, (0 * Math.PI) / 180, (360 * Math.PI) / 180.true)
            this.ctx.closePath()
            this.ctx.fill()
        }
Copy the code

Define the motion animation of the ball


        startevent() {
            var easing = 1 // Speed of motion
            let nvx = 100
            let self = this; (function frame() { // Write a self-executing function to prevent global variable contamination
                let globalID = window.requestAnimationFrame(frame)
                nvx = nvx + easing
                if (nvx < 700) {
                    // self.ctx.clearRect(0, 0, 800, 800)
                    self.initcanvascircle(nvx)
                } else {
                   window.cancelAnimationFrame(globalID) // End the animation}}}) (),Copy the code

Simple linear motion with variable speed

The speed of the ball is one hundredth of the remaining distance, and because the remaining distance is getting shorter and shorter, the final velocity is going to zero, so we have a ball that is moving at varying speeds

    startevent2() {
            let nvx = 100
            let self = this; (function frame() {
                // Write a self-executing function to prevent global variable contamination
                let globalID = window.requestAnimationFrame(frame)
                nvx = nvx + (700 - nvx) * 0.01
                if (nvx < 700) {
                    // self.ctx.clearRect(0, 0, 800, 800)
                    self.initcanvascircle(nvx)
                } else {
                    window.cancelAnimationFrame(globalID) // End the animation}}}) ()Copy the code

Draw a simple pendulum ball (let’s consider the friction-free case, the ball would keep going, but gravity would slow it down).

Since the ball is not accelerating in a straight line, (it’s a little complicated, so we simulate it as accelerating in a straight line)

Initialize the pendulum pattern

// degree Initial pendulum Angle
initcanvasZb(degree) {
            let x = 400 + 200 * Math.cos(degree)
            let y = 100 + 200 * Math.sin(degree)
            // Draw the background
            /* this.ctx.fillStyle = '#EEEEEE' this.ctx.fillRect(0, 0, 1260, 800) this.ctx.strokeStyle = '#000000' this.ctx.strokeRect(1, 1, 1258, 798) */
            this.ctx.clearRect(0.0.1260.800)
            // Start drawing the ball
            this.ctx.beginPath()
            this.ctx.fillStyle = 'HotPink'
            this.ctx.arc(x, y, 50, (0 * Math.PI) / 180, (360 * Math.PI) / 180.true)
            this.ctx.closePath()
            this.ctx.fill()
            // Start drawing the graph cycloid
            this.ctx.strokeStyle = 'HotPink'
            this.ctx.moveTo(400.100)
            this.ctx.lineTo(x, y)
            this.ctx.stroke()
        },
Copy the code

Define pendulum animation, initial Angle, initial velocity, and acceleration

2. Make sure to draw a circle first. Call fill ().


startevent3() {
            let nvx = 60 // Initial Angle
            let speed = 0 // Initial velocity
            let aspeed = 0.01 // Initial acceleration
            let self = this; (function frame() {
                // Write a self-executing function to prevent global variable contamination
                let globalID = window.requestAnimationFrame(frame)
                if (nvx >= 60 && nvx < 90) {
                    // Judge the critical value
                    if (speed < 0 && nvx + speed < 60) {
                        speed = 0
                        nvx = 60
                    } else {
                        speed += aspeed
                        nvx = nvx + speed
                    }
                    // self.ctx.clearRect(0, 0, 800, 800)
                    self.initcanvasZb((nvx * Math.PI) / 180)}else if (nvx >= 90 && nvx <= 120) {
                    if (speed > 0 && nvx + speed > 120) {
                        speed = 0
                        nvx = 120
                    } else {
                        speed -= aspeed
                        nvx = nvx + speed
                    }
                    self.initcanvasZb((nvx * Math.PI) / 180()})}}),Copy the code

Motion of solar system

Initialize the sun
    // Initialize the sun
        initSun() {
            this.ctx.beginPath()
            this.ctx.arc(300.300.50, (0 * Math.PI) / 180, (360 * Math.PI) / 180.true)
            this.ctx.closePath()
            this.ctx.fillStyle = 'HotPink'
            this.ctx.fill()
        },
Copy the code
Initialize the earth’s trajectory
// Initialize the earth trajectory
        initEarthgj() {
            this.ctx.beginPath()
            this.ctx.arc(300.300.200, (0 * Math.PI) / 180, (360 * Math.PI) / 180.true)
            this.ctx.closePath()
            this.ctx.strokeStyle = '#e01f15'
            this.ctx.stroke()
        },

Copy the code
Initialize earth
// Initialize the earth
        initEarth(addindex) {
            this.ctx.beginPath()
            let x = 300 + Math.cos((addindex * Math.PI) / 720) * 200
            let y = 300 + Math.sin((addindex * Math.PI) / 720) * 200
            this.ctx.arc(x, y, 20, (0 * Math.PI) / 180, (360 * Math.PI) / 180.true)
            this.ctx.closePath()
            this.ctx.fillStyle = '#987b7b'
            this.ctx.fill()
            this.initMouthgj(x, y)
            this.initMouth(x, y, addindex)
        },
Copy the code
Map the trajectory of the moon to initialize the moon

// Map the trajectory of the moon
        // Initialize the moon
        initMouthgj(x, y) {
            this.ctx.beginPath()
            this.ctx.arc(x, y, 50, (0 * Math.PI) / 180, (360 * Math.PI) / 180.true)
            this.ctx.closePath()
            this.ctx.strokeStyle = '#ccc'
            this.ctx.stroke()
        },
        initMouth(x, y, addindex) {
            this.ctx.beginPath()
            let x1 = x + Math.cos((addindex * Math.PI) / 360) * 50
            let y1 = y + Math.sin((addindex * Math.PI) / 360) * 50
            this.ctx.arc(x1, y1, 10, (0 * Math.PI) / 180, (360 * Math.PI) / 180.true)
            this.ctx.closePath()
            this.ctx.fillStyle = '#987b7b'
            this.ctx.fill()
        }
Copy the code
The object begins to move, defining the motion animation
run() {
            // eslint-disable-next-line
            let addindex = 0
            let _self = this; (function goframe() {
                _self.ctx.clearRect(0.0.600.600)
                let globalID = window.requestAnimationFrame(goframe)
                _self.initSun()
                _self.initEarthgj()
                _self.initEarth(addindex)
                if (addindex < 1440) {
                    addindex++
                } else {
                    addindex = 0}}}) (),Copy the code

Above are some simple Canvasl animations

  • Bezier curve twice and three times
  • Elastic collisions, frictional collisions
  • , etc.

Zhejiang Dahua Technology Co., Ltd.- Soft Research – Smart city Product RESEARCH and development Department recruitment senior front end, welcome to talk, interested can send resume to [email protected] all kinds of benefits, less overtime. Fish for fish.