canvas学习笔记2_点动画

186 阅读1分钟

绘制如图动画

image.png

说明: 主要使用了canvas的globalCompositeOperation属性,从而实现图像的合成。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>散点动画</title>
    <style>
        html,
        body {
            padding: 0;
            margin: 0;
            width: 100%;
            height: 100%;
            background: #000001;
        }
        
        canvas {
            background: #000001;
        }
    </style>
</head>

<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
    let speed = 0.5;
    let size = 0;
    let max = 20;
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    let width = 500;
    let height = 500;

    function render() {
        let animationCtx = ctx;     
        
        draw(animationCtx);
        
        size += speed;
        if (size > max) {
            size = 0;
        }

        // 这里使用# canvas globalCompositeOperation 属性
        animationCtx.fillStyle = 'rgba(0,0,0,0.95)';
        var prev = animationCtx.globalCompositeOperation;
        animationCtx.globalCompositeOperation = 'destination-in';
        animationCtx.fillRect(0, 0, width, height);
        // console.log('prev: ', prev) // source-over(默认属性)
        animationCtx.globalCompositeOperation = prev;
    }

    function draw(animationCtx) {
        animationCtx.beginPath();
        var pixel = {
            x: 100,
            y: 100
        };
        animationCtx.strokeStyle = 'red';
        animationCtx.arc(pixel.x, pixel.y, size, 0, Math.PI * 2);
        animationCtx.stroke();
        animationCtx.closePath();
    }

    (function animloop() {
        window.requestAnimationFrame(animloop);
                    // window.setInterval(animloop,2000) // 测试用(黑色红色合成效果)
        render()
    })()
</script>
</body>

</html>