简体   繁体   English

抽出 canvas JavaScript

[英]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.对于我的程序,假设有 200 个单元,每个单元可以处于 5 个不同的状态。 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.最初,它们都从 state 0 开始,它们可以随机跳转到状态 1 到 4,并影响其他单元也跳转。 This way, the more units are on state 2, the more units will jump to state 2 and so on.这样,state 2 上的单元越多,跳转到 state 2 的单元越多,依此类推。 I have these units moving randomly inside my canvas, bouncing off the walls when they hit them.我让这些单元在我的 canvas 内随机移动,当它们撞到它们时会从墙上弹开。 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.我现在想做的一件事是在图表上可视化演变,为此我希望 canvas 的一侧有单位跳跃状态,旁边有图表,动态表示 state 0 中的单位百分比, 1, 2... 同时。 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.我大概在编码图表时没有问题,但是我找不到在 canvas 之外或不改变它的情况下显示它的方法。 Just in case, I am programming in Atom and have mostly used p5 libraries.以防万一,我在 Atom 中编程并且主要使用 p5 库。 Any ideas??有任何想法吗??

You have 2 options:您有 2 个选项:

  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:制作第二个 canvas(就像 enhzflep 说的那样),但这对您来说可能很复杂,因为您将无法访问第二个 canvas 上的 P5.js 绘图工具,看看这个:

(On your first canvas) (在你的第一幅画布上)

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

To make and draw to a second canvas:制作并绘制第二个 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或者,您可以只使用您的第一个 canvas,并将专用于图形的部分分区
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).第二个选项更容易阅读,并且会为您省去一些麻烦(我会使用它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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