function draw() {}

Category:Game Lab

The lines of code contained inside its block are continuously executed until the program is stopped.

You can make your drawings come to life using animation with the draw() function. Think of it as a virtual flip book. The default rate of 30 frames per second can be reset by assigning a new value to World.frameRate.

There can only be one draw() function for each sketch, and draw() must exist if you want the code to run continuously, or to process events such as mouseDown().

Examples

Mouse-Controlled Dots

Draw random sized dots where the mouse is clicked.

// Draw random sized dots where the mouse is clicked.
function draw() {
  if (mouseDown("leftButton")) {
    strokeWeight(randomNumber(10, 20));
    point(World.mouseX,World.mouseY);
  }
}

function draw() {
  strokeWeight(randomNumber(10, 20));
  point(randomNumber(0, 400), randomNumber(0, 400));
}

TV Static Line

Animate a line like on a broken old television.

// Animate a line like on a broken old television.
var yPos = 0;
function draw() {  
  background("white");
  yPos = yPos - 1;
  if (yPos < 0) {
    yPos = 400;
  }
  line(0, yPos, 400, yPos);
}

Syntax

function draw() {
  
}

Returns

No return value.

Tips

  • draw() is called automatically and should never be called explicitly.
  • When animating a drawing using the draw() function, you need to redraw the entire image, back to front, not just the part that is moving.
  • To help debug your sprites use $watch in the debug window to watch variable or sprite property.

Found a bug in the documentation? Let us know at documentation@code.org