HTML5 Canvas animation effect implementation principle

Source: Internet
Author: User

HTML5 Canvas animation effect implementation principle


Online Demo

The HTML5 canvas can help us quickly achieve simple animation effects. The basic principle is as follows:

Draw a graph and clear it at a certain time to simulate an animation process. You can use context. clearRect (0, 0, x, y) to refresh the graph to be drawn.

The first method is to draw a graph, as follows:

function myAnimation() {    ctx.clearRect(0, 0, canvas_size_x, canvas_size_y);    if (x_icon < 0 || x_icon > canvas_size_x - size_x) {        stepX = -stepX;    }        if (y_icon < 0 || y_icon > canvas_size_y - size_y) {        stepY = -stepY;    }    x_icon += stepX;    y_icon += stepY;    ctx.drawImage(anim_img, x_icon, y_icon);}

The preceding method clears the canvas content at a certain time and recalculates the drawing position. If the size of the canvas is exceeded, the coordinates are reversed.

The following is the actual drawing method:

function draw() {    var canvas = document.getElementById("canvas");    ctx = canvas.getContext("2d");        anim_img = new Image(size_x, size_y);        anim_img.onload = function() {        setInterval('myAnimation()', 5);    }        anim_img.src = 'http://www.gbtags.com/gb/networks/avatars/80x8013d6393f-a44c-4180-8cb6-7bf0e4776283.png';}

The above method defines the image and calls the method for actually drawing the animation!

If you are interested in HTML5 animation rendering or want to learn how to simulate the physical animation effect, please read the following interactive tutorial and believe it will help you better understand the HTML canvas:

Particle Motion effects implemented by HTML5 canvas

Source: HTML5 Canvas animation effect implementation principle

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.