KineticJS - Get the width/height of a Path Shape?

送分小仙女□ 提交于 2019-12-08 11:52:09

问题


this is a big issue for me at the moment...

I'm rendering a world map via Path shapes... problem is the Path Shape does not offer width or height, so caching or other simple operations become really hard to do.

e.g. what x/y height/width to I give to path.toImage ?


Any idea how I could get around this problem?


回答1:


If the world map path is made up of a series of lines (as it often is), you can get the bounding box of the path by looking for the minX/minY and maxX/maxY coordinates in your path data.




回答2:


I just had to solve this same problem with Kinetic JS.

This code below looks through some random canvas draw code which contains (x,y) coordinates, extracts the coordinates into an array, looks through for the min and max of both X and Y, and shows the width and height of the shape.

From this you should have a bounding box.

var regex = /[+-]?\d+\.\d+/g;

var str = 'ctx.bezierCurveTo(30.1, 220.7, 82.8, 233.0, 147.8, 233.0); ctx.bezierCurveTo(213.1, 233.0, 266.6, 220.8, 266.6, 205.7); ctx.bezierCurveTo(266.6, 205.3, 267.0, 205.1, 267.0, 204.7);';

var floats = str.match(regex).map(function(v) { return parseFloat(v); });

console.log(floats);

      var minX = 99999;
      var maxX = -99999;
      var minY = 99999;
      var maxY = -99999;


      for ( var i = 0; i < floats.length; i++ ) {

          if ( isOdd(i) ) { // the array of numbers is in the form (x,y,x,y,x,y,x...)

              // Check Y values
              if ( floats[i] < minY ) { minY = floats[i]; }
              if ( floats[i] > maxY ) { maxY = floats[i]; }

          } else {

              // Check X values
              if ( floats[i] < minX ) { minX = floats[i]; }
              if ( floats[i] > maxX ) { maxX = floats[i]; }

          }

      }



       console.log('minX = ' + minX + ', minY = ' + minY + ', maxX = ' + maxX + ', maxY = ' + maxY);


function isOdd(num) { return num % 2;}


来源:https://stackoverflow.com/questions/17640513/kineticjs-get-the-width-height-of-a-path-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!