开发者

How to group objects in a net, on the screen?

I'm making a simu开发者_JAVA百科lation of the thinking and remembering process, and I have various pictures (cow, airplane, orange) that need to be displayed in a mind map-like style on the screen. Each object is connected to three others, as well, and it needs to look like a net.

What algorithm can I use? Also, I'm using JS, but pseudo code or an explanation would be nice too.


  • First get your data into a usable structure:
  • Draw your nodes in order, also drawing siblings with IDs larger then the current node.
  • You need to draw your siblings around the current node at 120 degree offsets to make your web (3 siblings, 360/3 = 120).

Some JavaScript to illustrate.

// initialize your data
var nodes = {
    1: {src: "imageA", siblings: [2,3,4]},
    2: {src: "imageB", siblings: [1,5,6]},
    3: {src: "imageC", siblings: [1,7,8]},
    4: {src: "imageD", siblings: [1,9,10]},
    5: {src: "imageE", siblings: [2]},
    6: {src: "imageF", siblings: [2]},
    7: {src: "imageG", siblings: [3]},
    8: {src: "imageH", siblings: [3]},
    9: {src: "imageI", siblings: [4]},
    10: {src: "imageJ", siblings: [4]},
}

// initialize some constats we will use
var DIST = 200; //pixel distance between images
var IMGW = 64; // image width
var IMGH = 64; // image height
var SCX = 400; // center screen x position
var SCY = 400; // center screen y position
var DEGSSTART = 90; // starting degrees offset
var DEGFLIP = 180; // add to flip the direction
var DEGSTEP = 120; // circle 360 / 3
// note: if you have more than 3 siblings change DEGSTEP appropriately

// the main function
function drawWeb(nodes, id, cx, cy, prevDeg) {
 var node = nodes[id];
 // draw the current node/image
 var xOff = cx - (IMGW / 2);
 var yOff = cy - (IMGH / 2);
 drawImage(node.src, Math.round(xOff), Math.round(yOff));
 // draw the siblings recursively
 var newDeg = prevDeg + DEGFLIP + DEGSTEP; 
 for(var i=0; i<node.siblings.length; i++) {
  var newId = node.siblings[i];
  if(newId > id) {
   // convert to radians and calc new location
   var rad = newDeg * Math.PI / 180;
   var newCX = cx + DIST * Math.cos(rad);
   var newCY = cy + DIST * Math.sin(rad);
   drawWeb(nodes, newId, newCX, newCY, newDeg);
   newDeg += DEGSTEP;
  }
 }
}

// the draw function you can customize
// use jquery or some other method
function drawImage(src, x, y) {
 // fill in code to put an image on your screen
 console.log(src + ': ' + x + ', ' + y);
}

// test
drawWeb(nodes, 1, SCX, SCY, 90);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜