algorithm - How to convert an closed path SVG to a 0-1 array -


lets there svg closed filled rectangle in middle , around there's white space of 2 points .

<path d="m2 2 h 3 v 3 h 2 z" fill="transparent" stroke="black"/> 

so want represent 2-d matrix white space represented 0 , black spaces (covered area) represented 1. example should be-

 [    [0, 0, 0, 0],    [0, 1, 1, 1],    [0, 1, 1, 1],    [0, 1, 1, 1]  ] 

it's simple path , i'm trying find way work complex paths including bezier curve. i'm trying convert svg world map 0-1 matrix can run ai algorithms on .

implemented @robert longson suggestion. 1) draw svg in canvas 2) imagedata canvascontext array 3) iterate on array , form matrix. 4) array returned getimagedata flat array , consecutive 4 array index correspond 1 point of canvas , r, g, b , alpha (rgba) of color of point.

here's working react component .

import react, { component } '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 = [];      (let row = 0, count = -1; row < canvaswidth; row++) {       imagetomat[row] = [];       // imagetomat[row][col] = 'rgba(' + imagedata[++count] + ', ' + imagedata[++count] + ', ' + imagedata[++count] + ', ' + imagedata[++count] + ')';       (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);   } } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -