学堂 学堂 学堂公众号手机端

如何用JS实现画笔的功能,代码是什么

lewis 1年前 (2024-04-29) 阅读数 13 #技术
今天就跟大家聊聊有关“如何用JS实现画笔的功能,代码是什么”的内容,可能很多人都不太了解,为了让大家认识和更进一步的了解,小编给大家总结了以下内容,希望这篇“如何用JS实现画笔的功能,代码是什么”文章能对大家有帮助。

实现功能


鼠标点击时可以在画板上画画
如果鼠标双击那么停止
移动进画板颜色改变移除时颜色改变

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
 </head>
 <style>
  * {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
  }
  .drawbox {
   width: 1100px;
   height: 600px;
   background-color: skyblue;
   position: relative;
  }
 </style>
 <body>
  <div class="drawbox"></div>
  <script>
   /*
    1.鼠标点击时可以在画板上画画
    如果鼠标双击那么停止
    移动进画板颜色改变移除时颜色改变
    */
   var darwbox = document.querySelector("div");
   darwbox.onmouseenter = function() {
    darwbox.style.backgroundColor = "red";
   };
   darwbox.onmouseleave = function() {
    darwbox.style.backgroundColor = "skyblue";
   };
   var istrue = false;
   darwbox.onmousedown = function(e) {
    istrue = true;
   };
   darwbox.onmousemove = function(e) {
    if (istrue == true) {
     var x = e.pageX;
     var y = e.pageY;
     var circle = document.createElement("div");
     circle.style.width = "10px";
     circle.style.height = "10px";
     circle.style.backgroundColor = "#fff";
     circle.style.position = "absolute";
     circle.style.left = x - 5 + "px";
     circle.style.top = y - 5 + "px";
     circle.style.borderRadius = "50%";
    
     darwbox.appendChild(circle);
    }
   };
   darwbox.onmouseup = function(e) {
    istrue = false;
   };
  </script>
 </body>
</html>

效果图:


这篇关于“如何用JS实现画笔的功能,代码是什么”的文章就介绍到这了,更多相关的内容,欢迎关注博信,小编将为大家输出更多高质量的实用文章!
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门