html 旋转渐变、极坐标渐变、按角度渐变

问题

欸呦图丢了

本来想做SVG渐变,但是查资料发现SVG不能做这种转圈的渐变,于是乎想在SVG中插入<foreignObject>然后直接画出渐变或者直接上图片,画出来的话,占用空间更小一点而且分辨率没有太多限制,除非分辨率太高需要很久才能画完。

代码

<!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>
        canvas {
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="100" height="100"></canvas>
</body>
<script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext("2d");
    var w = canvas.width;
    var h = canvas.height;
    const CX = w / 2;
    const CY = h / 2;
    const OFFSET = 90;//旋转角度
    const START = 90;//开始渐变角度
    const RANGE = 180;//渐变角度
    const ROUNT = 360;//周角
    const WHITE = 255;//最亮颜色值
    for (var y = 0; y < h; y++) {
        for (var x = 0; x < w; x++) {
            var theta = (Math.atan2(y - CY, x - CX) + Math.PI) / (Math.PI * 2) * (ROUNT - 1);
            theta = (theta + OFFSET) % ROUNT + START
            theta = Math.max(Math.min(Math.floor(((ROUNT - 1) - theta) / RANGE * WHITE), WHITE), 0);
            var color = theta.toString(16);
            while (color.length < 2) {
                color = '0' + color
            }
            color = '#000000' + color
            ctx.fillStyle = color;
            ctx.fillRect(x, y, 1, 1)
        }
    }
</script>

</html>

posted on 2021-08-19 16:22  星云*  阅读(279)  评论(0编辑  收藏  举报