Create a draw() function inside other function in Javascript Processing

1.9k views Asked by At

Ok, so I have this piece of code:

 var a = 0;
 var left = random(width);
 var right = left +50;
 var pos = left;
 var isLeft = true;

 var draw= function() {
    background(255, 0, 0);
    fill(255, 0, 0);
    strokeWeight(2);
    stroke(255, 255, 255);
    ellipse(pos,400-a,10,10); 
    a=a+0.5;
    if (isLeft === true) {
        pos +=0.5;
    }
    if (pos === right) {
        isLeft = false;
    }
    if (isLeft === false) {
        pos -=0.5;
    }
    if (pos === left) {
        isLeft = true;
    }
 };

Basically all it does is create a bubble that floats upwards while moving left and right just a little bit. My idea is to make it so that this only happens/starts when I click the mouse. But I don't seem to know how. I am still learning how to code. Anyone can help me produce the desired effect.

Thanks you and sorry for my bad english.

3

There are 3 answers

1
a_pradhan On

If your function is called draw and your button's ID is draw-start, then add an event listener to the button which calls the function.

document.getElementById('draw-start').addEventListener('click', function(){ draw(); }, false);

However, if you want to start the animation if the click happens on the canvas in which you are drawing, and canvas ID is draw-canvas then,

document.getElementById('draw-canvas').addEventListener('click', function(){ draw(); }, false);
1
mikeb On

You need to use the onclick event to make javascript execute on a click. However, your draw function is also broken. This shows you how to call the javscript when something is clicked:

<html>
<head>
<script>


function draw() {
   alert('draw stuff')
};
</script>
</head>
<body>
<button onclick="draw()">Click me</button>
</body>
</html>

You can try it here on jsfiddle

0
Konstantin Dinev On

If you just want it to happen if you click anywhere then this example should work for you:

document.body.addEventListener("click", draw, false);