js realizes drawing

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>js实现画图</title>
    <style type="text/css">
      #xy {
    
    
        position: fixed;
        left: 0;
        bottom: 0;
      }
      .box {
    
    
        border-radius: 50%;
        position: absolute;
      }
      input {
    
    
        position: absolute;
        z-index: 999999999999;
      }
      input:nth-child(2) {
    
    
        left: 50px;
      }
      input:nth-child(3) {
    
    
        left: 100px;
      }
    </style>
  </head>
  <body>
    <input type="button" name="" id="btn1" value="+" />
    <input type="button" name="" id="btn2" value="-" />
    <input type="button" name="" id="red" value="red" />
    <span id="xy"></span>
  </body>
  <script type="text/javascript">
    // 1 获取节点
    var btnsObj = document.querySelectorAll("input");
    var btn1Obj = btnsObj[0];
    var btn2Obj = btnsObj[1];
    var btn3Obj = btnsObj[2];
    var spanObj = document.getElementById("xy");
    // div背景颜色
    var c = "black";
    // div宽高的设置
    var w = (h = 8);
    /*******必须是按下的时候,滑过才显示******/
    // 2 给document绑定鼠标移动事件
    document.onmousedown = function (event) {
    
    
      // 嵌套一个移动事件
      document.onmousemove = function () {
    
    
        // 获取事件对象
        var e = window.event || event;
        // 获取鼠标实相对于文档的时的位置
        var mouseX = e.pageX;
        var mouseY = e.pageY;
        // 将实时的位置放到页面左下角
        spanObj.innerHTML = mouseX + "," + mouseY;
        /******动态创建div,鼠标经过后显示******/
        var divObj = document.createElement("div");
        // 设置div的定位
        divObj.style.position = "absolute";
        divObj.style.top = mouseY + "px";
        divObj.style.left = mouseX + "px";
        // 设置背景颜色
        divObj.style.background = c;
        // 设置div的宽高
        divObj.style.width = w + "px";
        divObj.style.height = h + "px";
        // 设置div为圆的
        divObj.style.borderRadius = "50%";
        // 追加到页面中
        document.body.appendChild(divObj);
      };
    };

    // 鼠标抬起来的时候,清除移动事件
    document.onmouseup = function () {
    
    
      document.onmousemove = null;
    };

    /*******点击控制div的大小******/
    btn1Obj.onclick = function () {
    
    
      w += 2;
      h += 2;
    };
    btn2Obj.onclick = function () {
    
    
      w -= 2;
      h -= 2;
    };
    //点击之后改变div颜色
    btn3Obj.onclick = function () {
    
    
      c = "red";
    };
  </script>
</html>

The effect is as follows:
Insert image description here

Reference blog: https://blog.csdn.net/m0_52217128/article/details/120516286?spm=1001.2101.3001.6650.5&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5-120516286 -blog-89309983.pc_relevant_recovery_v2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-5-120516286-blog-89309983.pc_relevant_recovery_v2&utm_relevant_index=8

Guess you like

Origin blog.csdn.net/qdm13209211861/article/details/128095507