美文网首页
canvas使背景图像模糊并剪裁头像

canvas使背景图像模糊并剪裁头像

作者: 苍老师的眼泪 | 来源:发表于2022-01-20 13:56 被阅读0次
    image.png
    <!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>Document</title>
    
        <style>
            html,
            body {
                padding: 0;
                margin: 0;
            }
        </style>
    </head>
    
    <body>
    
        <img id="img" alt="">
    
        <canvas id="canvas" style="display: none;"></canvas>
    
        <script>
            let canvas = document.getElementById("canvas")
    
            let bg_img = new Image()
            bg_img.src = "174cf7fbbe5cb9f82905636e1ab1e33b.jpeg"
    
            let avatar = new Image()
            avatar.src = "63495249.jpeg"
    
            window.onload = function() {
    
                let width = document.documentElement.clientWidth
                let height = document.documentElement.clientHeight
    
                canvas.width = width
                canvas.height = canvas.width / 16 * 9
    
                let ctx = canvas.getContext("2d")
    
                ctx.save()
    
                ctx.filter = "blur(3px)"
    
                ctx.drawImage(bg_img, 0, 0, canvas.width, canvas.height)
    
                ctx.restore()
    
                let avatar_radius = 60
    
                ctx.save()
                ctx.arc(canvas.width / 2, canvas.height / 2, avatar_radius, 0, 2 * Math.PI);
                ctx.clip()
                ctx.drawImage(avatar, canvas.width / 2 - avatar_radius, canvas.height / 2 - avatar_radius, avatar_radius * 2, avatar_radius * 2)
                ctx.restore()
    
                img.src = canvas.toDataURL()
    
            }
        </script>
    </body>
    
    </html>
    

    相关文章

      网友评论

          本文标题:canvas使背景图像模糊并剪裁头像

          本文链接:https://www.haomeiwen.com/subject/cnyjhrtx.html