Home Web Front-end H5 Tutorial Implementation code of Canvas screensaver animation in html5

Implementation code of Canvas screensaver animation in html5

Aug 15, 2018 am 09:56 AM

The content of this article is about the implementation code of Canvas screensaver animation in HTML5. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Without further ado, let’s get straight to the code

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body style="height:760px">
    <canvas id="canvas" style="border:0px red solid;display:none">
    </canvas>
    </body>
    </html>
Copy after login

Due to project requirements, the animation needs to display real-time updated data, so it is different from the ordinary canvas drawing. But you can't draw html directly into canvas, don't worry, there is a way.

In order to draw HTML content, you must first use the <foreignObject> element to contain the HTML content, and then draw the SVG image into your canvas.

To put it bluntly, the only really tricky thing here is creating the SVG image. All you need to do is create an SVG containing an XML string and then construct a Blob according to the following sections.

  1. The MIME of the blob object should be "image/svg xml".

  2. A <svg> element.

  3. The <foreignObject> element contained in the SVG element.

  4. The (formatted) HTML wrapped in <foreignObject>.

As mentioned above, by using an object URL, we can inline the HTML instead of loading it from an external source. Of course, you can also use external sources as long as the domain is the same as the original document (not across domains).

  //创建画布
    var Cans=document.getElementById("canvas");    
    var ctx=Cans.getContext("2d");    //设置全屏画布
    Cans.width=document.body.offsetWidth;
    Cans.height=document.body.offsetHeight;    
    var DOMURL,img,svg,url;
    initimg("AAA");//默认显示数据,一下代码参考https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas
    function initimg(data) {        
    var data = '<svg xmlns="http://www.w3.org/2000/svg" width="52" height="52">' +
            '<foreignObject width="100%" height="100%">' +
            '<p xmlns="http://www.w3.org/1999/xhtml" style="font-size:12px">' +
            '<p style="width:50px;height:50px;border:1px red solid">' +
            ''+data+'</p>' +
            '</p>' +
            '</foreignObject>' +
            '</svg>';
        DOMURL = window.URL || window.webkitURL || window;
        img = new Image();
        svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
        url = DOMURL.createObjectURL(svg);
        img.src = url;
    }    
    //每隔五秒刷新数据,随机从数组中取(实际情况当然是要从后台获取)
    var getdata = setInterval(function () {        
    var data=["BBB","CCC","DDD","EEE"]
        initimg(data[Math.floor(Math.random()*8)]);
    },5000)
Copy after login

The following is to control the display position of animation, trigger animation and close animation

var raf;    
var arror = [];    
var running = false;    
//绘制图形
    function createStar() {        
    return {
            x: 0,
            y: 0,
            vx: 0.7,
            vy: 0.7,//用来控制移动速度
            draw: function() {
                ctx.drawImage(img, this.x, this.y);
                DOMURL.revokeObjectURL(url);
            }
        }
    }    
    //清除
    function clear() {
        ctx.fillStyle = 'rgba(255,255,255,1)';
        ctx.fillRect(0,0,canvas.width,canvas.height);
    }    
    //判断图形坐标是否超出画布范围
    function draw() {
        clear();
        arror.forEach(function(ball, i){
            ball.draw();
            ball.x += ball.vx;
            ball.y += ball.vy;            
            if (ball.y + ball.vy+50 > canvas.height || ball.y + ball.vy < 0) {
                ball.vy = -ball.vy;
            }            
            if (ball.x + ball.vx+50 > canvas.width || ball.x + ball.vx < 0) {
                ball.vx = -ball.vx;
            }
        });
        raf = window.requestAnimationFrame(draw);
    }
    
    canvas.addEventListener('click',function (e) {
        event.preventDefault();
        window.cancelAnimationFrame(raf);            if(!running){
                Cans.style.display="none"
                document.onmousemove = document.onkeydown = document.onclick = null;
                clearTimeout(timer);
                clearInterval(getdata);
                clear();
            }else{
                running = false;
                bindevent(1);
            }
    })    
    function loadpi() {        
    if (!running) {
            raf = window.requestAnimationFrame(draw);
            running = true;
        }        var ball;
        ball = createStar();
        ball.x = canvas.width/2-25;
        ball.y = canvas.height/2-25;        
        arror.push(ball);
        document.onmousemove = document.onkeydown = document.onclick = null;
        clearTimeout(timer);
    }    
    var timer;    
    function bindevent(it) {
        clearTimeout(timer);
        timer = setTimeout(function () {            
        if(it==1){
                raf = window.requestAnimationFrame(draw);
                running = true;
            }else{
                Cans.style.display="block"
                loadpi();
            }
        }, 3000);
    }
    window.onload = document.onmousemove = document.onkeydown = document.onclick = function () {
        bindevent();
    }
Copy after login

Related recommendations:

Loading loading animation based on HTML5 Canvas and Rebound animation Special effects

Use H5 canvas to make horror animation

canvas and JS to implement dynamic clock animation

The above is the detailed content of Implementation code of Canvas screensaver animation in html5. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

What exactly does H5 page production mean? What exactly does H5 page production mean? Apr 06, 2025 am 07:18 AM

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

How to make h5 click icon How to make h5 click icon Apr 06, 2025 pm 12:15 PM

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

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

What is the H5 programming language? What is the H5 programming language? Apr 03, 2025 am 12:16 AM

H5 is not a standalone programming language, but a collection of HTML5, CSS3 and JavaScript for building modern web applications. 1. HTML5 defines the web page structure and content, and provides new tags and APIs. 2. CSS3 controls style and layout, and introduces new features such as animation. 3. JavaScript implements dynamic interaction and enhances functions through DOM operations and asynchronous requests.

What application scenarios are suitable for H5 page production What application scenarios are suitable for H5 page production Apr 05, 2025 pm 11:36 PM

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.

How to make pop-up windows with h5 How to make pop-up windows with h5 Apr 06, 2025 pm 12:12 PM

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the &lt;canvas&gt; tag to draw graphics or using JavaScript to control interaction behavior.

See all articles