简体   繁体   中英

Draw out of canvas JavaScript

I have been developing a program which includes some sort of genetic algorithm. For my program, let's say there is a population of 200 units, and each unit can be in 5 different states. Inititlly, they all start at state 0, and they can randomly jump to states 1 to 4, and influence other units to jump as well. This way, the more units are on state 2, the more units will jump to state 2 and so on. I have these units moving randomly inside my canvas, bouncing off the walls when they hit them. The one thing I want to do now is visualize the evolution on a chart, and for that I would like to have the canvas with the units jumping states on one side and the chart next to it, dynamically representing the percentage of units in state 0, 1, 2... simultaneously. I will presumably have no problem in coding the chart, however I cannot find a way of displaying it outside the canvas or without altering it. Just in case, I am programming in Atom and have mostly used p5 libraries. Any ideas??

You have 2 options:

  1. Make a second canvas (Like enhzflep said), but this might be complicated for you, becuase you will not have access to P5.js drawing tools on that second canvas, look at this:

(On your first canvas)

fill(255,0,0)
rect(50,50,50,50);

To make and draw to a second canvas:

const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
//deal with positioning, scaling, and other stuff (comment if you need help with that)
...

const c = canvas.getContext('2d');
c.fillStyle = "rgb(255,0,0)";
c.fillRect(50,50,50,50);

(See, lots of effort)

  1. Or, you can just use your first canvas, and partition a section off that is dedicated to the graph
createCanvas(600 + graphWidth, 600);

//Wherever your bouncing off walls code is
//for the right side of the screen

if(this.x > width - graphWidth){
  bounce();
}

//that leaves you a graphWidth by 600 rectangle for you to draw you graph

The second option is much easier to read and will save you some headaches (I would use that).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM