search
HomeWeb Front-endJS TutorialIssues related to text avoidance in front-end algorithms (detailed tutorial)

This article mainly introduces you to the relevant information about text avoidance in the front-end algorithm. I believe many friends do not know this knowledge, but they will be amazed when they see the effect. The main use of inMap text to achieve this effect is The avoidance function is introduced in detail through sample code in this article. Friends who need it can refer to it. Let’s learn it together.

Preface

inMap is a big data visualization library based on canvas, focusing on the visual display of big data direction points, lines and surfaces. Currently supports scatter, fence, thermal, grid, aggregation and other methods; committed to making big data visualization simple and easy to use.

GitHub address: https://github.com/TalkingData/inmap (local download)

Document address: http://inmap.talkingdata.com/

at In geographic information visualization, we often encounter the need to mark text on the map. The following shows the effect of a popular chart chart frame:

The text space to be displayed When it is not enough, it will cause overlapping text and confusing display, making the user experience very unfriendly.

How to solve this problem? We use text avoidance algorithm to solve this cheating problem.

The following shows the inMap text avoidance effect:

Text labeling algorithm is one of the most complex problems in GIS (belongs to NP complexity problem, so the optimal solution cannot usually be found, only the better solution).

inMap The avoidance algorithm uses the quartile model algorithm. Next, I will teach you step by step how to write the avoidance algorithm. An experienced driver will help you show off and help you fly.

Prepare data

inMap receives latitude and longitude data and needs to map it to the pixel coordinates of the canvas, which uses Mercator Conversion, Mercator's algorithm is very complicated. We will have a separate article to explain its principles in the future. After conversion, the data you get should look like this:

[
 {
 "name": "海门",//要显示的文字
 "lng": 121.15,
 "lat": 31.89,
 "count": 7,
 "pixel": { //像素坐标
  "x": 968,
  "y": 736
 }
 },
 {
 "name": "鄂尔多斯",
 "lng": 109.781327,
 "lat": 39.608266,
 "count": 5,
 "pixel": {
  "x": 659,
  "y": 478
 }
 },
...
]

Okay, now that we have the converted pixel coordinate data (x, y), we can do the following.

Find the actual size of each text rectangle

measureText() is a built-in method of canvas, which returns the pixel unit of the font width:

let ctx = this.container.getContext('2d'); // canvas 上下文
let width= ctx.measureText(name).width;

We get the width of each text through measureText. Canvas does not have a direct method to obtain the text. So how do we get the height of the text?

We found through repeated testing that when the font of canvas is equal to the "13px Arial" font (other fonts cannot be guaranteed), the height of the text is about 1.1 times the fontSize.

So the code is as follows:

let fontSize = parseInt(ctx.font);
let height = fontSize * 1.1;

After the width and height of the text are obtained, we can create the coordinate system of the text rectangle.

Create a quartile model

The so-called quartile model, each marker point has There are four places for text on the top, bottom, left and right. If you can't put it on the left side, try putting it on the right side. If it still doesn't work, try putting it on the bottom. And so on. The principle is that simple, haha.

Create a description of the coordinates of the virtual rectangle on the right:

The description of the coordinates of the virtual rectangle on the right also includes dots to prevent text and Dots overlap.

There are some pitfalls when calculating the height of the virtual rectangle. The size of the dots is not fixed, but is dynamically configured according to the user. The diameter of the dots may be greater than the height of the text, so we set the height of the virtual rectangle to always be It's the largest one and requires some special handling.

The code is as follows:

_getLeftAnchor() {
  let x = this.center.x - this.radius - this.textReact.width,
    y = this.center.y - this.textReact.height / 2,
    diam = this.radius * 2,
    maxH = diam > this.textReact.height ? diam : this.textReact.height; //矩形的高度
  return {
    x,
    y,
    minX: x,
    maxX: this.center.x + this.radius,
    minY: this.center.y - maxH / 2,
    maxY: this.center.y + maxH / 2
  };
}

And so on, describing the coordinates of the virtual rectangle below, left, and above.

Determine collision

Determine whether two rectangles cover and intersect. The intersection is determined based on the minX, maxX, minY, maxY of the rectangle. The principle is relatively simple. , the code is as follows:

/**
 * 判断分位是否相交
 * @param {*} target 
 */ 
isAnchorMeet(target) {
  let react = this.getCurrentRect(),
    targetReact = target.getCurrentRect();
  if ((react.minX < targetReact.maxX) && (targetReact.minX < react.maxX) &&
    (react.minY < targetReact.maxY) && (targetReact.minY < react.maxY)) {
    return true;
  }
  return false;
}

Create a virtual text collection object

let labels = pixels.map((val) => {
  let radius = val.pixel.radius + this.style.normal.borderWidth; //圆点半径
  return new Label(val.pixel.x, val.pixel.y, radius, fontSize, byteWidth, val.name);
});

Recursively traverse the virtual text collection and determine whether it intersects with others. If there is an intersection Just move the current text position until they no longer intersect. When you can't find a suitable location, choose to hide the current text.

The code is as follows:

do {
  var meet = false; //本轮是否有相交
  for (let i = 0; i < labels.length; i++) {
    let temp = labels[i];
    for (let j = 0; j < labels.length; j++) {
      if (i != j && temp.show && temp.isAnchorMeet(labels[j])) {
        temp.next();
        meet = true;
        break;
      }
    }
  }
} while (meet);

Painting text

labels.forEach(function (item) {
  if (item.show) { //是否显示
    let pixel = item.getCurrentRect();
    ctx.beginPath();
    ctx.fillText(item.text, pixel.x, pixel.y);
    ctx.fill();
  }
});

The text avoidance algorithm has been introduced so far, the corresponding inMap file address It is https://github.com/TalkingData/inmap/blob/master/src/worker/helper/Label.js. I will continue to share useful information with you in the future.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

related articles:

How to fix the header and first column in Vue

How express multer implements the image upload function

Native JS How to implement a music player

How to set user permissions in VueJS

How to use YDUI’s ScrollTab component in WeChat applet

The above is the detailed content of Issues related to text avoidance in front-end algorithms (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

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
The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment