search
HomeWeb Front-endH5 Tutorialjavascript html5 canvas implements draggable province map of China

This article mainly introduces the relevant information on the implementation of the Chinese map of draggable provinces using javascript html5 canvas. Friends in need can refer to it.

The example of this article shares the implementation of the Chinese map of draggable provinces in html5 canvas. Method, for your reference, the specific content is as follows

1. Data acquisition
Drawing a map requires province boundary coordinates. In theory, you can use Baidu API to obtain data and draw every time, but In order to increase efficiency, all coordinates are first obtained and stored in the database.
Create a new province data array

Copy code The code is as follows:

var allZoneData = [{&#39;name&#39;:&#39;辽宁省&#39;,&#39;been&#39;:&#39;yes&#39;,&#39;id&#39;:&#39;01&#39;},<span style="font-family: Arial, Helvetica, sans-serif;">{&#39;name&#39;:&#39;吉林省&#39;,&#39;been&#39;:&#39;yes&#39;,&#39;id&#39;:&#39;02&#39;},……];</span>

Poll the array, request Baidu API to obtain coordinate data based on the province name, and Relax the data to php in ajax mode

var myGeo = new BMap.Geocoder(); 
 
(function(){ 
 for(var i = 0;i < allZoneData.length;i++){ 
  getAllZone(allZoneData[i].name,allZoneData[i].been,allZoneData[i].id); 
 } 
})(); 
//name为省份名,been表示是否去过,id为唯一标识,cir为省份圈号(有可能一个省份有两部分封闭圆圈构成) 
function getAllZone (name,been,id) { 
 var data,temp; 
         
 var bdary = new BMap.Boundary(); 
 bdary.get(name, function(rs){ 
  var count = rs.boundaries.length;  
  for(var j = 0; j < count; j++){      
   var ply = new BMap.Polygon(rs.boundaries[j], {strokeWeight: 2, strokeColor: "#ff0000"}); 
   data = ply.getPath(); 
   $.ajax({ 
    url: "addData.php", 
    type:"POST", 
    data: {&#39;data&#39;:data,&#39;name&#39; : name,&#39;cir&#39;:j,&#39;been&#39;:been,&#39;id&#39;:id}, 
    success: function(txt){ 
     console.log(txt); 
    }, 
    error: function(){ 
     alert(&#39;添加数据出错!&#39;); 
    } 
   });   
  }         
 });         
}

After php gets the data, parse the data and store the data into the pre-built database

<?php 
  header("content-type:text/html; charset=utf-8"); 
  $data = $_REQUEST[&#39;data&#39;]; 
  $name = $_REQUEST[&#39;name&#39;]; 
  $cir = $_REQUEST[&#39;cir&#39;]; 
  $been = $_REQUEST[&#39;been&#39;]; 
  $id = $_REQUEST[&#39;id&#39;]; 
 
  $con = mysql_connect("localhost","……","……"); 
  if (!$con){ 
    die(&#39;Could not connect: &#39; . mysql_error()); 
  } 
  mysql_select_db("……", $con); 
  mysql_set_charset(&#39;utf8&#39;,$con); 
 
  foreach ($data as $temp){ 
    $sql = "insert into place (id,name,lng,lat,cir,been) values (&#39;".$id."&#39;, &#39;".$name."&#39;, &#39;".$temp[&#39;lng&#39;]."&#39;,&#39;".$temp[&#39;lat&#39;]."&#39;,&#39;".$cir."&#39;,&#39;".$been."&#39;)"; 
    if (!mysql_query($sql,$con)){ 
      die(&#39;Error: &#39; . mysql_error()); 
    } 
  } 
 
  mysql_close($con); 
  echo &#39;Success&#39;; 
?>

2. Draw a map (the base map is drawn on the mapCanvas layer)
Poll the province array and use ajax Request the boundary coordinates of the province, and then draw

var drawMap = function (context,data,l,t) { //context为绘制所在的层,l和t为相对位置,data为边界对象数组 
 if(data.been == &#39;yes&#39;){ 
  context.fillStyle = "green"; 
 }else{ 
  context.fillStyle = "grey"; 
 } 
 context.globalAlpha = 0.8; 
 context.beginPath(); 
 cleft = (data.coordinate[0].lng - temp_left) * bigger + l; //temp_left和temp_top为地图偏移位置. 
 ctop = (temp_top - data.coordinate[0].lat) * bigger + t; //bigger为放大倍数 
 
 context.moveTo(cleft,ctop); 
           
 for(var j = 1;j < data.coordinate.length;j++){ 
  cleft = (data.coordinate[j].lng - temp_left) * bigger + l; 
  ctop = (temp_top - data.coordinate[j].lat) * bigger + t; 
  context.lineTo(cleft,ctop); 
 } 
           
 context.closePath(); 
 context.stroke(); 
 context.fill(); 
}

3. Draw the moving connection line (the connecting line and the moving province are drawn on the moveMapCanvas layer )
When dragging a province on the map, several straight lines connecting the moved province and the original province will appear

##

var drawLinkLine = function(data,l,t){ //此处的l和t表示移动的相对位置 
 for(var k = 0;k < data.coordinate.length;k++){ 
  if(k % 60 == 0){ 
   moveMapContext.beginPath(); 
           
   //根据移动距离的不同,设置连线的粗细 
   lineLength = Math.sqrt(l * l + t * t) / 100; 
   lineLength = lineLength >= 4.5 ? 4.5 : lineLength; 
   moveMapContext.lineWidth = 5 - lineLength; 
 
   moveMapContext.strokeStyle = "rgba(0,120,60,0.4)"; 
   cleft = (data.coordinate[k].lng - temp_left) * bigger; 
   ctop = (temp_top - data.coordinate[k].lat) * bigger; 
   moveMapContext.moveTo(cleft,ctop); 
 
   cleft = (data.coordinate[k].lng - temp_left) * bigger + l; 
   ctop = (temp_top - data.coordinate[k].lat) * bigger + t; 
   moveMapContext.lineTo(cleft,ctop); 
   moveMapContext.closePath(); 
   moveMapontext.stroke(); 
  } 
 } 
}

4. EventMouse press event: When you click on the map, what you need to do is to determine the click location, convert the location information into longitude and latitude, and then obtain the province name based on the longitude and latitude through Baidu API .

$(&#39;#eventCanvas&#39;).mousedown(function(ev){ 
 //获取点击canvas的坐标 
 var mouseX, mouseY; 
 if(ev.layerX || ev.layerX==0){ 
  mouseX = ev.layerX; 
  mouseY = ev.layerY; 
 }else if(ev.offsetX || ev.offsetX==0){ 
  mouseX = ev.offsetX; 
  mouseY = ev.offsetY; 
 } 
 
 //保存点击时的原坐标值 
 tempX = mouseX; 
 tempY = mouseY; 
 
 //将坐标转化为经纬度 
 mouseX = mouseX/bigger + temp_left; 
 mouseY = temp_top - mouseY/bigger; 
 
 if(opts.dragAll){ 
  draging = true; 
 }else{ 
  moveMapContext.clearRect(0, 0, 1100, 630); 
  //根据经纬度获得所在地理位置并获取边界坐标再画线 
  myGeo.getLocation(new BMap.Point(mouseX, mouseY), 
   function(result){ 
    tempName = &#39;&#39;; 
    draging = true; 
    name = result.addressComponents.province; 
    tempName = name; 
    pubFuns.drawMoveLayerLine(0,0);    
  }); 
 } 
});

Mouse movement event: obtain data based on the clicked province name, and redraw the province of the mobile layer in real time


$(&#39;#eventCanvas&#39;).mousemove(function(ev){ 
 var mouseX, mouseY; 
 if(ev.layerX || ev.layerX==0){ 
  mouseX = ev.layerX; 
  mouseY = ev.layerY; 
 }else if(ev.offsetX || ev.offsetX==0){ 
  mouseX = ev.offsetX; 
  mouseY = ev.offsetY; 
 } 
 if(draging){ 
  if(opts.dragAll){ <span style="font-family: Arial, Helvetica, sans-serif;">//拖动整个地图,存在问题,地图画的太慢</span> 
   mapContext.clearRect(0, 0, 1100, 630); 
   for(var i = 0;i < allZoneData.length;i++){ 
    for(var j = 0;j < allData[allZoneData[i].name].length;j++){ //allData是第一次读取数据时放到内存里的变量,它包含了所有数据 
     pubFuns.drawMap(mapContext,allData[allZoneData[i].name][j],mouseX - tempX, mouseY - tempY); 
    } 
   } 
   }else{ 
    moveMapContext.clearRect(0, 0, 1100, 630); 
    pubFuns.drawMoveLayerLine(mouseX - tempX, mouseY - tempY); 
   }  
  } 
});

Mouse lift event: Set dragging to false and clear the moving layer.


$(&#39;#eventCanvas&#39;).mouseup(function(e){ 
 if(opts.dragAll){  
 }else{ 
  moveMapContext.clearRect(0, 0, 1100, 630); 
 } 
 draging = false; 
});

Summary: The functions and principles are very simple, but you can be familiar with some properties and methods of canvas. Canvas layers can be overlapped together, so that different content can be drawn on different layers to facilitate maintenance and management.

The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

About HTML5 to implement image compression upload function

##

The above is the detailed content of javascript html5 canvas implements draggable province map of China. 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
H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor