Canvas绘制N边形头像框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<style>
    body{
        background-color: black;
    }
</style>
<body>
<canvas id="test"></canvas>
<script>
    function createTx(id,imgUrl,width=100,height=100,vertices=6) {
        var divobj = document.getElementById(id);
        divobj.width = width;
        divobj.height = height;
        var widthBc = divobj.width;
        var heightBc = divobj.height;
        var imgContext = divobj.getContext("2d");
        var imgObj = new Image();
        imgObj.src = imgUrl;
        imgObj.onload = function () {
            imgContext.drawImage(this, 0, 0,widthBc,heightBc);
            imgContext.globalCompositeOperation="destination-in";

            var length = widthBc / 2;

            var getDegree = function(vertices, index) {
                return 360 / vertices * (i + 0.5) + 360 / vertices;
            }

            var getRadian = function(degree) {
                return degree * Math.PI / 180;
            };

            imgContext.beginPath();
            for (var i = 0; i < vertices; i++) {
                var degree = getDegree(vertices, i),
                    radian = getRadian(degree);

                var x = Math.cos(radian) * length + widthBc / 2;
                var y = Math.sin(radian) * length + widthBc / 2;
                imgContext.lineTo(x, y);
            }
            imgContext.closePath();
            imgContext.fill();
        }
    }

    createTx('test', './caomei.jpg')
</script>
</body>
</html>

效果图:

YDM7G1GJISE4H4(3N5ONR[E.png

阅读数:293
如有疑问请与我联系:点击与我联系