search
HomeWeb Front-endJS TutorialRequireJS simple drawing program development

Foreword

The emergence of RequireJS makes it easy to modularize front-end code. When front-end projects become larger and larger and there are more and more codes, modular code makes the project structure clearer, not only making our ideas clearer during development. Clear and easier to maintain later. The following is a simple drawing program I developed using RequireJS after learning RequireJS. It runs in the browser as shown below:

RequireJS simple drawing program development

Start

The project structure of this simple drawing program is as shown below:

where index .html is the homepage of the project. All js files are stored in the js directory. The js/app directory is our customized module file. There are currently no files in the js/lib directory. When our project uses some other front-end frameworks such as jquery, etc. , the js/lib directory stores the js files of these frameworks. js/main.js is the configuration file of requirejs, which mainly configures some paths. js/require.min.js is the file of the RequireJS framework. Please follow me step by step to complete this simple drawing program!

1. Configure requirejs

The configuration file code of this project is placed in js/main.js. The code content is as follows:

require.config({
  baseUrl: 'js/lib',
  paths: {
    app: '../app'
  }
})


The main thing is to configure the project root directory as 'js/lib', and then A path named 'app' is configured, and the path is '../app', which is the 'js/app' directory.

2. Write module code

The main modules in this project are as follows: point.js, line.js, rect.js, arc.js, utils.js, which are explained one by one below:

point.js :

point.js This module represents a point (x, y), the code is as follows:

/** 点 */
define(function() {
  return function(x, y) {
    this.x = x;
    this.y = y;
    this.equals = function(point) {
      return this.x === point.x && this.y === point.y;
    };
  };
})


The above code uses define to define the point module, and returns a class in the callback function. The class has two parameters x, y, and an equals method for comparing whether two points are equal.
To use this module, we can use the following code:

require(['app/point'], function(Point) {
  //新建一个点类的对象
  var point = new Point(3, 5);
})


It should be noted here that the first parameter of the require() function is an array, and the Point in the callback function represents our point class, through Create an object of point class using new Point().

line.js: The

line.js module represents a straight line, the code is as follows:

/** 直线 */
define(function() {
  return function(startPoint, endPoint) {
    this.startPoint = startPoint;
    this.endPoint = endPoint;
    this.drawMe = function(context) {
      context.strokeStyle = "#000000";
      context.beginPath();
      context.moveTo(this.startPoint.x, this.startPoint.y);
      context.lineTo(this.endPoint.x, this.endPoint.y);
      context.closePath();
      context.stroke();
    }
  }
})


The definition of the line module is similar to the definition of the point module, both return a in the define callback function Class, the construction method of this straight line class has two point class parameters, representing the starting point and end point of the straight line. The straight line class also has a drawMe method, which draws itself by passing in a context object.

rect.js: The

rect.js module represents a rectangle. The code is as follows:

/** 矩形 */
define(['app/point'], function() {
  return function(startPoint, width, height) {
    this.startPoint = startPoint;
    this.width = width;
    this.height = height;
    this.drawMe = function(context) {
      context.strokeStyle = "#000000";
      context.strokeRect(this.startPoint.x, this.startPoint.y, this.width, this.height);
    }
  }
})


where startPoint is the coordinate of the upper left corner of the rectangle and is a point class. Width and height represent the width and height of the rectangle respectively. , and there is also a drawMe method to draw the rectangle itself.

arc.js: The

arc.js module represents a circle. The code is as follows:

/** 圆形 */
define(function() {
  return function(startPoint, radius) {
    this.startPoint = startPoint;
    this.radius = radius;
    this.drawMe = function(context) {
      context.beginPath();
      context.arc(this.startPoint.x, this.startPoint.y, this.radius, 0, 2 * Math.PI);
      context.closePath();
      context.stroke();
    }
  }
})


where startPoint represents the coordinates of the upper left corner of the rectangle where the circle is located, and radius represents the radius of the circle. The drawMe method is a method for drawing a circle.
In the above modules, the straight line class, rectangle class, and circle class all contain the drawMe() method, which involves the knowledge of canvas drawing. If you are not sure, you can check the document: HTML 5 Canvas Reference Manual

utils.js

utils.js module is mainly used to process various graphics drawing tools, including the drawing of straight lines, rectangles, and circles, as well as recording and clearing drawing trajectories. The code is as follows:

/** 管理绘图的工具 */
define(function() {
  var history = []; //用来保存历史绘制记录的数组,里面存储的是直线类、矩形类或者圆形类的对象
 
  function drawLine(context, line) {
    line.drawMe(context);
  }
 
  function drawRect(context, rect) {
    rect.drawMe(context);
  }
 
  function drawArc(context, arc) {
    arc.drawMe(context);
  }
 
  /** 添加一条绘制轨迹 */
  function addHistory(item) {
    history.push(item);
  }
 
  /** 画出历史轨迹 */
  function drawHistory(context) {
    for(var i = 0; i < history.length; i++) {
      var obj = history[i];
      obj.drawMe(context);     
    }
  }
 
  /** 清除历史轨迹 */
  function clearHistory() {
    history = [];
  }
 
  return {
    drawLine: drawLine,
    drawRect: drawRect,
    drawArc: drawArc,
    addHistory: addHistory,
    drawHistory: drawHistory,
    clearHistory: clearHistory
  };
})


3. Write interface code and handle mouse events

The modules of this simple drawing program have been defined above. The above modules are used when drawing graphics. Next, we will start writing the main interface. The code is here. The main interface contains four buttons and a large canvas for drawing. The code of the index.html file is directly uploaded below:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>简易绘图程序</title>
  <style type="text/css">
    canvas {
      background-color: #ECECEC;
      cursor: default; /** 鼠标设置成默认的指针 */
    }
    .tool-bar {
      margin-bottom: 10px;
    }
  </style>
</head>
<body>
  <div class="tool-bar">
    <button id="btn-line">画直线</button>
    <button id="btn-rect">画矩形</button>
    <button id="btn-oval">画圆形</button>
    <button id="btn-clear">清空画布</button>
    <span id="hint" style="color: red;">当前操作:画直线</span>
  </div>
  <canvas id="canvas" width="800" height="600"></canvas>
  <script type="text/javascript" src="js/require.min.js" data-main="js/main"></script>
  <script type="text/javascript">
    require([&#39;app/point&#39;, &#39;app/line&#39;, &#39;app/rect&#39;, &#39;app/arc&#39;, &#39;app/utils&#39;],
      function(Point, Line, Rect, Arc, Utils) {
 
      var canvas = document.getElementById("canvas");
      var context = canvas.getContext(&#39;2d&#39;);
      var canvasRect = canvas.getBoundingClientRect(); //得到canvas所在的矩形
      canvas.addEventListener(&#39;mousedown&#39;, handleMouseDown);
      canvas.addEventListener(&#39;mousemove&#39;, handleMouseMove);
      canvas.addEventListener(&#39;mouseup&#39;, handleMouseUp);
      bindClick(&#39;btn-clear&#39;, menuBtnClicked);
      bindClick(&#39;btn-line&#39;, menuBtnClicked);
      bindClick(&#39;btn-rect&#39;, menuBtnClicked);
      bindClick(&#39;btn-oval&#39;, menuBtnClicked);
 
      var mouseDown = false;
      var selection = 1; // 0, 1, 2分别代表画直线、画矩形、画圆
 
      var downPoint = new Point(0, 0),
        movePoint = new Point(0, 0),
        upPoint = new Point(0, 0);
      var line;
      var rect;
      var arc;
 
      /** 处理鼠标按下的事件 */
      function handleMouseDown(event) {
        downPoint.x = event.clientX - canvasRect.left;
        downPoint.y = event.clientY - canvasRect.top;
        if(selection === 0) {
          line = new Line(downPoint, downPoint);
          line.startPoint = downPoint;
        } else if(selection === 1) {
          rect = new Rect(new Point(downPoint.x, downPoint.y), 0, 0);
        } else if(selection === 2) {
          arc = new Arc(new Point(downPoint.x, downPoint.y), 0);
        }
        mouseDown = true;
      }
 
      /** 处理鼠标移动的事件 */
      function handleMouseMove(event) {
        movePoint.x = event.clientX - canvasRect.left;
        movePoint.y = event.clientY - canvasRect.top;
        if(movePoint.x == downPoint.x && movePoint.y == downPoint.y) {
          return ;
        }
        if(movePoint.x == upPoint.x && movePoint.y == upPoint.y) {
          return ;
        }
        if(mouseDown) {
          clearCanvas();
          if(selection == 0) {
            line.endPoint = movePoint;
            Utils.drawLine(context, line);
          } else if(selection == 1) {
            rect.width = movePoint.x - downPoint.x;
            rect.height = movePoint.y - downPoint.y;
            Utils.drawRect(context, rect);
          } else if(selection == 2) {
            var x = movePoint.x - downPoint.x;
            var y = movePoint.y - downPoint.y;
            arc.radius = x > y ? (y / 2) : (x / 2);
            if(arc.radius < 0) {
              arc.radius = -arc.radius;
            }
            arc.startPoint.x = downPoint.x + arc.radius;
            arc.startPoint.y = downPoint.y + arc.radius;
            Utils.drawArc(context, arc);
          }
          Utils.drawHistory(context);
        }
      }
 
      /** 处理鼠标抬起的事件 */
      function handleMouseUp(event) {
        upPoint.x = event.clientX - canvasRect.left;
        upPoint.y = event.clientY - canvasRect.top;
 
        if(mouseDown) {
          mouseDown = false;
          if(selection == 0) {
            line.endPoint = upPoint; 
            if(!downPoint.equals(upPoint)) {
              Utils.addHistory(new Line(new Point(downPoint.x, downPoint.y),
                new Point(upPoint.x, upPoint.y)));
            } 
          } else if(selection == 1) {
            rect.width = upPoint.x - downPoint.x;
            rect.height = upPoint.y - downPoint.y;
            Utils.addHistory(new Rect(new Point(downPoint.x, downPoint.y), rect.width, rect.height));
          } else if(selection == 2) {
            Utils.addHistory(new Arc(new Point(arc.startPoint.x, arc.startPoint.y), arc.radius));
          }
          clearCanvas();
          Utils.drawHistory(context);
        }
      }
 
      /** 清空画布 */
      function clearCanvas() {
        context.clearRect(0, 0, canvas.width, canvas.height);
      }
 
      /** 菜单按钮的点击事件处理 */
      function menuBtnClicked(event) {
        var domID = event.srcElement.id;
        if(domID === &#39;btn-clear&#39;) {
          clearCanvas();
          Utils.clearHistory();
        } else if(domID == &#39;btn-line&#39;) {
          selection = 0;
          showHint(&#39;当前操作:画直线&#39;);
        } else if(domID == &#39;btn-rect&#39;) {
          selection = 1;
          showHint(&#39;当前操作:画矩形&#39;);
        } else if(domID == &#39;btn-oval&#39;) {
          selection = 2;
          showHint(&#39;当前操作:画圆形&#39;);
        }
      }
 
      function showHint(msg) {
        document.getElementById(&#39;hint&#39;).innerHTML = msg;
      }
 
      /** 给对应id的dom元素绑定点击事件 */
      function bindClick(domID, handler) {
        document.getElementById(domID).addEventListener(&#39;click&#39;, handler);
      }
    });
  </script>
</body>
</html>


There are many codes in the index.html file. But the most important code is to monitor and process the three events of mouse pressing, moving, and lifting. In addition, one thing to note when obtaining the coordinate position of the mouse in the canvas: since the clientX and clientY obtained in the event object are relative to the mouse The coordinates of the page. In order to obtain the coordinates of the mouse in the canvas, you need to obtain the rectangular area where the canvas is located, and then use clientX-canvas.left and clientY-canvas.top to obtain the position of the mouse in the canvas.

Known bug

When drawing a circle, you need to drag the mouse from the upper left corner to the lower right corner to draw the circle. If not, there will be problems with the position of the circle.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version