Home  >  Article  >  Web Front-end  >  Implementation code of Canvas screensaver animation in html5

Implementation code of Canvas screensaver animation in html5

不言
不言Original
2018-08-15 09:56:162589browse

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>

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)

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();
    }

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