代码之家  ›  专栏  ›  技术社区  ›  ProfK

如何用可点击的位置绘制网页图

  •  0
  • ProfK  · 技术社区  · 10 年前

    以前从未这样做过,但我认为人们习惯于捕捉点击的位置(如果可能的话),并将其映射到位图图像中的某个位置。这对我来说就像是一堆麻烦,尤其是在调整图像大小时。

    现在我怀疑一个更好的方法是有一个SVG图像,其中嵌入了锚元素,因此它们可以通过调整大小来调整位置。

    还有其他方法吗?

    2 回复  |  直到 10 年前
        1
  •  2
  •   grabantot    8 年前

    使用svg是最简单的选择。使用svg。js、raphal或snap。svg或其他库。我更喜欢svg。js(插件可用,面向对象,某些方法的语法糖,轻量级),但基本上它们都是一样的,尽管它们都不是完美的。下面是创建可点击行的代码(保存到.html文件并运行,不要忘记下载svg.js):

    <div id="svg"></div>
    <script src="svg.js"></script>
    <script>
    onload = function() {
        var draw = SVG('svg') //we are going to draw in a div with id='svg'
    
        var line = draw.line('30%', 80, 180, 60) //coords can be in %, px or other css units
        line.attr( { 'stroke': '#f00', 'stroke-width': 5 } ) //styled with css
          //there are also shortcut methods like stroke('#f00')
        .on('click', function() { draw.text('click') }) //method calls can be chained
    }
    </script>
    

    Svg元素是html的一部分,它们使用css进行样式设置,因此操作它们要容易得多。

    下载svg。js,参见示例 https://svgdotjs.github.io/installation/

    阅读文档: https://svgdotjs.github.io

    忘掉映射吧,它枯燥乏味,很难维护。可能还有其他选项,但我怀疑还有比svg更简单的东西(如果你使用库的话)。

    既然您考虑使用映射来在图表上创建可点击的位置,我想您不会绘制一些琐碎的图表,现有的图表库(有很多基于svg或不基于svg的)不会为您服务。编写一个可以使用您选择的svg库绘制图表的库应该不难。

    为了制作这样一个库,我只需要编写函数(或包装对象)来绘制每类对象(每类一个函数),这些对象需要视觉表示加上两个辅助函数(例如坐标系之间的转换)。

        2
  •  0
  •   Jim Garrison    10 年前

    这是通过 usemap 的属性 img object 标记以及关联的 map 标签包含 area 定义任意形状的标记,每个形状都可以与 href .

    以下示例来自当前 HTML5 spec draft at W3C

    <p>
     Please select a shape:
     <img src="shapes.png" usemap="#shapes"
          alt="Four shapes are available: a red hollow box, a green circle, a blue triangle, and a yellow four-pointed star.">
     <map name="shapes">
      <area shape=rect coords="50,50,100,100"> <!-- the hole in the red box -->
      <area shape=rect coords="25,25,125,125" href="red.html" alt="Red box.">
      <area shape=circle coords="200,75,50" href="green.html" alt="Green circle.">
      <area shape=poly coords="325,25,262,125,388,125" href="blue.html" alt="Blue triangle.">
      <area shape=poly coords="450,25,435,60,400,75,435,90,450,125,465,90,500,75,465,60"
            href="yellow.html" alt="Yellow star.">
     </map>