Canvas screensaver animation

Posted by hezll on Thu, 02 Jan 2020 22:47:39 +0100

Don't talk much, go 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>

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

To draw HTML content, you need to use the <foreignObject> Element contains HTML content, and then draws the SVG image into your canvas.

 

The only really tricky thing here, to exaggerate, is to create SVG images. All you need to do is create a XML SVG of string, and then construct a Blob.

  1. The MIME of the blob object should be 'image/svg+xml'.
  2. One <svg> Element.
  3. The <foreignObject> Element.
  4. Wrap up <foreignObject> HTML in.

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

  //Create canvas
    var Cans=document.getElementById("canvas");
    var ctx=Cans.getContext("2d");
    //Set full screen canvas
    Cans.width=document.body.offsetWidth;
    Cans.height=document.body.offsetHeight;
    var DOMURL,img,svg,url;
    initimg("AAA");//Data is displayed by default. Refer to the code below 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%">' +
            '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:12px">' +
            '<div style="width:50px;height:50px;border:1px red solid">' +
            ''+data+'</div>' +
            '</div>' +
            '</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;
    }

    //Refresh the data every five seconds and randomly take it from the array (the actual situation is, of course, to get it from the background)
    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 the animation, trigger the animation and close the animation

var raf;
    var arror = [];
    var running = false;
    //Drawing graphics
    function createStar() {
        return {
            x: 0,
            y: 0,
            vx: 0.7,
            vy: 0.7,//Used to control movement speed
            draw: function() {
                ctx.drawImage(img, this.x, this.y);
                DOMURL.revokeObjectURL(url);
            }
        }
    }
    //Eliminate
    function clear() {
        ctx.fillStyle = 'rgba(255,255,255,1)';
        ctx.fillRect(0,0,canvas.width,canvas.height);
    }
    //Determine whether the graphic coordinates are beyond the canvas range
    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();
    }

Topics: Javascript xml