选择复杂图形区域

项目中经常会遇到选择一个复杂图片的某个区域,然后做点击或其他操作。
如在这个图片上,分别点击上中下三个区域做不同的操作。


btn.png

处理方法:
1.把图片导入ai中,把需要点击的区域的轮廓分别用钢笔工具画出来,颜色填充或者线描边,图层顺序:轮廓在背景上面,如下图所示,导出svg。


image.png

2.svg中path(也就是选择的轮廓)的样式直接设置fill填充颜色或者stroke描边颜色,去掉style样式

<svg xmlns="http://www.w3.org/2000/svg" 
xmlns:xlink="http://www.w3.org/1999/xlink" 
viewBox="0 0 78 199">
<defs>
<!-- <style>.cls-1{fill:none;stroke:grba(0,0,0,0);stroke-miterlimit:10;}
</style> -->
</defs>
<g id="btn" data-name="btn">
<image width="78" height="199" xlink:href="btn-operate.png"/>
</g>

<g id="top">
<polygon cursor='pointer'  points="7.82 78 7.82 26.04 36.32 6.64 38.82 10.02 41.65 6.64 69.32 23.64 69.82 78 38.82 59.97 7.82 78"/>
</g>

<g id="bottom">
<polygon  cursor='pointer'  points="7.82 123.05 7.82 173.84 35.32 192.64 39 189.03 42.32 192.64 69.82 173.21 69.82 123.05 39 140.53 7.82 123.05"/>
</g>

<g id="center">
<polygon cursor='pointer'  points="39 59.97 2.32 80.64 2.32 119.51 39 139.91 75.32 119.64 75.32 80.37 39 59.97"/>
</g>

</svg>

3.在js文件中使用<embed>标签展示svg图片,通过id获取每个区域,增加点击事件。
这里的id就是svg文件中<g>标签的id,也是ai软件中图层的名字,所以在ai中就可以把id名字命名好


export default function index() {
  useEffect(() => {
    const embed = document.querySelector('embed');
    // 加延迟是为了等dom挂载上
    setTimeout(() => {
      const dom = embed.getSVGDocument();
      if (dom) {
        const btnTop = dom.querySelector('#top'); // 这里的id就是svg文件中<g>标签的id,也是ai软件中图层的名字,所以在ai中就可以把id名字命名好
        const btnCenter = dom.querySelector('#center');
        const btnBottom = dom.querySelector('#bottom');
        btnTop.setAttribute('fill', 'rgba(0,0,0,0)');
        btnCenter.setAttribute('fill', 'rgba(0,0,0,0)');
        btnBottom.setAttribute('fill', 'rgba(0,0,0,0)');

        btnTop.addEventListener('mousedown', function () {
          console.log('放大');
        });

        btnCenter.addEventListener('mousedown', function () {
          console.log('旋转');
        });

        btnBottom.addEventListener('mousedown', function () {
          console.log('缩小');
        });
      }
    }, 100);
  }, []);

  return (
    <embed
      id="btn"
      src={operateBtn}
      width="78px"
      height="200px"
      type="image/svg+xml"
      pluginspage="http://www.adobe.com/svg/viewer/install/"
    />
  );
}

如此便可以对图片上不同的区域做操作了!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容