javascript - 将图像映射代码分解为单个对象的有效方法是什么?

标签 javascript html

我正在构建一个允许用户使用图像 map (他们在不同网站上创建)的应用程序。 目前,用户在其他站点制作图像 map 后,他们需要返回我的站点并手动输入不同区域(形状和坐标)。

我想自动化这个过程,所以用户只需复制粘贴整个代码片段,我就会自动提取各个区域。

例如,我希望用户输入以下代码:

<img src="Screenshot (473).png" alt="" usemap="#map" />
<map name="map">
    <area shape="rect" coords="866, 213, 1024, 357" />
    <area shape="rect" coords="965, 451, 1048, 512" />
    <area shape="circle" coords="1167, 200, 77" />
    <area shape="poly" coords="1357, 298, 1279, 376, 1394, 501, 1651, 386, 1511, 286" />
    <area shape="poly" coords="802, 250, 856, 499, 551, 536, 610, 262, 758, 181" />
</map>

然后当他们提交时,我会自动提取以下内容:

[
  {
    shape: "rect",
    coords: [866, 213, 1024, 357]
  },
  {
    shape: "rect",
    coords: [965, 451, 1048, 512]
  },
  {
    shape: "circle",
    coords: [1167, 200, 77]
  },
  {
    shape: "poly",
    coords: [1357, 298, 1279, 376, 1394, 501, 1651, 386, 1511, 286]
  },
  {
    shape: "poly",
    coords: [802, 250, 856, 499, 551, 536, 610, 262, 758, 181]
  }
]

我正在尝试找出解决此问题的最佳方法,但还没有找到任何优雅的方法。只是一个深度嵌套的 trim 操作。解决这个问题的“最干净”方法是什么?

最佳答案

这是一个有趣的!一个不太常用的 API。您正在寻找 DOMParser .

这需要一些“防止错误输入”的防御和清理,但是根据您提供的正确输入,我们可以做到这一点:

const sampleString = `
  <img src="Screenshot (473).png" alt="" usemap="#map" />
  <map name="map">
      <area shape="rect" coords="866, 213, 1024, 357" />
      <area shape="rect" coords="965, 451, 1048, 512" />
      <area shape="circle" coords="1167, 200, 77" />
      <area shape="poly" coords="1357, 298, 1279, 376, 1394, 501, 1651, 386, 1511, 286" />
      <area shape="poly" coords="802, 250, 856, 499, 551, 536, 610, 262, 758, 181" />
  </map>
`;

const domparser = new DOMParser();
const doc = domparser.parseFromString(sampleString, 'text/html');

const output = [...doc.querySelectorAll('area')].map(a => ({shape: a.shape, coords: a.coords.split(/,\s*/)}));

console.log(output);

关于javascript - 将图像映射代码分解为单个对象的有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61929608/

相关文章:

javascript - Cx 框架 : How to access a DOM element in Cx?

javascript - 从 JavaScript 转换 Ember.js 应用程序

javascript - AngularJS 未捕获错误 : [$injector:modulerr] -- noob here

Javascript(无 JQUERY)切换 Div

html - 带有页眉、页脚和正文的简单 div

javascript - 使用 Javascript 正确设置文本框的输入值

Python:发送带有嵌入式图像和附件的多部分 html 电子邮件

html - 如何去除底部的空白

javascript - jQuery,如果 "a"标签是否有类

javascript - 小标签不适用于输入标签