在处理草图中我得到了
int posX = 10;
int posY = 10;
int s = 12;
int vx,vy;
int red,gr,bl, =0;
void setup(){
size(200,200);
vx = random(6);
vy = random(6);
}
void draw(){
if(mousePressed){
red = r;
gr = g;
bl = b;
}
background(red,gr,bl);
fill(255);
posX += vx ;
posY += vy ;
if (posX > width || posX<0){
vx *= -1;
}
if(posY > height || posY < 0){
vy *= -1;
}
ellipse (posX,posY,s,s);
}
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="processing-1.4.1.js"></script>
</head>
<body>
<div id="msg">
</div>
<canvas id = "canvas" data-processing-sources="mixing.pde"></canvas>
<button onclick = "startSketch();">Start</button>
<button onclick = "stopSketch();">Stop</button>
<script type="application/javascript">
var processingInstance;
sp = 1;
function startSketch(){
switchSketchState(true);
}
function stopSketch(){
switchSketchState(false);
}
function switchSketchState(on){
if(!processingInstance){
processingInstance = Processing.getInstanceById('canvas');
}
if (on){
processingInstance.loop();
}
else{
processingInstance.noLoop();
}
alert(processingInstance.posX);// this return undefined i have to see 10
}
</script>
</body>
</html>
当我试图通过javascript访问posX变量并在屏幕上提醒它时浏览器告诉我它是未定义的。有没有办法访问变量并更改其值。
答案 0 :(得分:0)
您的草图有几个逻辑问题:您在int
和float
类型之间切换,并且您正在使用未定义的变量r
g
和{{1 }}
我强烈建议您在Java模式下编程,以便这些错误更加明显,然后在您准备部署时切换到JavaScript模式。
但你真正的问题是: Processing.js只允许你访问草图的功能,而不是它的变量。
如果你想在JavaScript中获得b
,那么你将不得不编写一个posX
函数,然后从JavaScript中调用它。
如果你想设置它也是一样的:创建一个getPosX()
函数,然后调用它。
答案 1 :(得分:0)
尝试此操作,它将在第67行的js中记录一个处理变量
<!--
from:
http://processingjs.org/articles/jsQuickStart.html
with added function getX(); to demonstrate how to pass variables from a processing sketch to javascript
-->
<html>
<head>
<title>Hello Web - Controlling Processing from JavaScript</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.6.6/processing.min.js"></script>
</head>
<body>
<script type="application/processing" data-processing-target="pjs">
int x=y=1;
int xVel=yVel=3;
int t = 300;
void setup() {
size(310, 200);
background(100);
stroke(255);
println('hello web!');
}
int getX() {
return t;
}
void draw(){
ellipse(x, y,10,10);
x = x + xVel;
y = y + yVel;
if ((x > width)||(x < 0)){
xVel = xVel * -1;
}
if ((y > height)||(y < 0)){
yVel = yVel * -1;
}
}
</script>
<button onclick="startSketch();">
Start</button>
<button onclick="stopSketch();">
Stop</button>
<canvas id="pjs" data-processing-sources="pjs"</canvas>
<script type="application/javascript">
var processingInstance;
function startSketch() {
switchSketchState(true);
}
function stopSketch() {
switchSketchState(false);
}
function switchSketchState(on) {
if (!processingInstance) {
processingInstance = Processing.getInstanceById('pjs');
}
if (on) {
processingInstance.loop();
console.log(processingInstance.getX());
} else {
processingInstance.noLoop(); // stop animation, call noLoop()
}
}
</script>
</body>
</html>
工作示例: