让我们说,有一个svg的封闭填充矩形在中间和周围,有一个2点的空白。
<path d="M2 2 H 3 V 3 H 2 Z" fill="transparent" stroke="black"/>因此,我想表示这个二维矩阵,其中所有的空白都表示为0,黑色空间(覆盖区域)表示为1。因此,在这个例子中,应该是-
[
[0, 0, 0, 0],
[0, 1, 1, 1],
[0, 1, 1, 1],
[0, 1, 1, 1]
]这是一条简单的路径,但我正在试图找到一种方法,它可以适用于复杂的路径,包括bezier曲线。实际上,我正在尝试将一个SVG世界地图转换为0-1矩阵,这样我就可以在它上运行一些人工智能算法。
发布于 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。
这是一个起作用的反应元件。
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);
}
}https://stackoverflow.com/questions/35264829
复制相似问题