首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将闭合路径SVG转换为0-1数组

如何将闭合路径SVG转换为0-1数组
EN

Stack Overflow用户
提问于 2016-02-08 08:02:34
回答 1查看 224关注 0票数 0

让我们说,有一个svg的封闭填充矩形在中间和周围,有一个2点的空白。

代码语言:javascript
运行
复制
<path d="M2 2 H 3 V 3 H 2 Z" fill="transparent" stroke="black"/>

因此,我想表示这个二维矩阵,其中所有的空白都表示为0,黑色空间(覆盖区域)表示为1。因此,在这个例子中,应该是-

代码语言:javascript
运行
复制
 [
   [0, 0, 0, 0],
   [0, 1, 1, 1],
   [0, 1, 1, 1],
   [0, 1, 1, 1]
 ]

这是一条简单的路径,但我正在试图找到一种方法,它可以适用于复杂的路径,包括bezier曲线。实际上,我正在尝试将一个SVG世界地图转换为0-1矩阵,这样我就可以在它上运行一些人工智能算法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-17 13:25:15

实施@Robert Longson建议。1)在画布中绘制svg,2) Get ImageData as CanvasContext Array 3)在该数组上迭代并形成矩阵。4)数组由getImageData返回是一个平面数组,consecutive 4 array index对应于画布的一个点,它们是该点颜色的r、g、b和alpha。

这是一个起作用的反应元件。

代码语言:javascript
运行
复制
import React, { Component } from 'react';

export default class IndexPage extends Component {

  constructor(properties) {
    super(properties);
    this.canvasWidth = 1052;
    this.canvasHeight = 580;
  }

  componentDidMount() {
    const mapCanvas = this.refs.canvas;
    const ctx = mapCanvas.getContext('2d');
    const img = new Image();
    img.onload = function() {
      ctx.drawImage(img, 0, 0);
      this.arrayFromSvg();
    }.bind(this);
    img.src = 'World.svg';
  }

  render() {
    return ( < div >
     < div styles={{
        width: this.canvasWidth,
        height: this.canvasHeight
      }
      } >
        < canvas width = {
      this.canvasWidth
      }
      height = {
      this.canvasHeight
      }
      ref = "canvas" >
        < /canvas> < /div >
        < /div>
      );
  }

  arrayFromSvg() {
    const mapCanvas = this.refs.canvas;
    const ctx = mapCanvas.getContext('2d');
    const canvasWidth = mapCanvas.width;
    const canvasHeight = mapCanvas.height;
    const imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight).data;
    const imageToMat = [];

    for (let row = 0, count = -1; row < canvasWidth; row++) {
      imageToMat[row] = [];
      // imageToMat[row][col] = 'rgba(' + imageData[++count] + ', ' + imageData[++count] + ', ' + imageData[++count] + ', ' + imageData[++count] + ')';
      for (let col = 0; col < canvasHeight; col++) {
        if (imageData[++count] + imageData[++count] + imageData[++count] + imageData[++count] > 0) {
          imageToMat[row][col] = 1;
        } else {
          imageToMat[row][col] = 0;
        }
      }
    }
    console.log(imageToMat);
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35264829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档