Use js to achieve an effect of random distribution by ellipse

Requirements: randomly distributed in the div, there are two colors, the font size is random, the name in the middle must be the largest, the effect is as follows.

 Code reference:

     // 获取div元素
        var container = document.getElementById("randoms");
        var centerX = container.offsetWidth / 2.5; // 椭圆的中心点横坐标
        var centerY = container.offsetHeight / 2.5; // 椭圆的中心点纵坐标
        var a = container.offsetWidth / 2.5; // 长轴的长度
        var b = container.offsetHeight / 2.5; // 短轴的长度
        var theta = 0; // 角度

        // 创建中间的span元素
        var middleSpan = document.createElement("span");
        middleSpan.innerText = "中间内容";
        middleSpan.style.fontSize = "26px";
        middleSpan.style.fontFamily = "微软雅黑";
        middleSpan.style.color = "#1B52FD";
        middleSpan.style.position = "absolute";
        middleSpan.style.top = centerY -30 + "px";
        middleSpan.style.left = centerX-30 + "px";
        container.appendChild(middleSpan);

        for (var i = 0; i < this.numbers.length; i++) {
          var number = this.numbers[i];
          var span = document.createElement("span");
          span.innerText = number;
          span.style.fontSize = Math.floor(Math.random() * 18 + 12) + "px";
          span.style.fontFamily = "微软雅黑";
          // 计算椭圆上的点的坐标
          var x = centerX + a * Math.cos(theta);
          var y = centerY + b * Math.sin(theta);

          // 确保不超出"randoms"这个div
          x = Math.max(0, Math.min(x, container.offsetWidth-30));
          y = Math.max(0, Math.min(y, container.offsetHeight-30));

          span.style.position = "absolute";
          span.style.top = y + 10+ "px";
          span.style.left = x + 10 + "px";

          var color = Math.floor(Math.random() * 2) === 0 ? "#1B52FD" : "#FE973E";
          span.style.color = color;

          if (i === Math.floor(this.numbers.length / 2)) {
            span.style.fontSize = "22px";
            span.style.color = "#FE973E";
          }
          container.appendChild(span);
          // 增加角度,使得下一个数字的位置在椭圆上均匀分布
          theta += (2.5 * Math.PI) / this.numbers.length;
        }

The source data: numbers:['admin','zxp','zxp1','admin','admin','admin','admin','admin'].

Just execute this method directly in Vue.

Guess you like

Origin blog.csdn.net/qq_42174597/article/details/131569681