I need to click a HTML button and change a value in processing.js. This seems like it would be simple, but something is wrong here:
<!DOCTYPE html>
<html>
<head>
<script src="../../processing.js"></script>
</head>
<body>
<script type="application/processing">
int color =80;
void setup() {
size(200, 200);
stroke(255);
}
void draw() {
background(0);
fill(color);
ellipse(100, 100, 160, 160);
}
function changeColor(newColor){
color = newColor;
}
</script>
<canvas width="200" height="200"></canvas></p>
<div style="height:0px;width:0px;overflow:hidden;"></div>
<button onClick="chang开发者_运维技巧eColor(150)">Change Color</button>
</body>
</html>
Change int color = 80;
to var color = 80;
and
<script type="application/processing">
to <script type="text/javascript">
and you should be good.
This is a concept known by the terms loose typing
and dynamic typing
(which means that a JS variable can hold different data types at different times depending on context). So, you don't define any types here.
To get this working, change your sketch function to:
int myColor = 80;
void changeColor(newColor) {
myColor = newColor;
}
change your button code to be the following:
<button onClick="Processing.instances[0].changeColor(150)">
Change Color
</button>
The reason it didn't work before is that
- The browser does not execute code in a
<script>
block unless it hastype="text/javascript'
. So unlike a normal JavaScript block, the changeColor function is not global to the page. - Since the function is not global, you need to refer to it through the Processing instance, with the
Processing.instances
array. - Your variable named
color
would stomp on the Processing API function calledcolor()
so I changed the name of your variable - I changed your JavaScript function to a Processing function; Processing.js attaches Processing functions to the sketch when parsing it, which means you can call it yourself later.
精彩评论