p5.js | translate() function

The translate() function in p5.js is used to specify the amount to displace objects within the display window. The x parameter is used to specify the left/right translation and y parameter is used to specify up/down translation.

Syntax:

translate(x, y, [z])

or

translate(vector)

Parameters: This function accepts three parameters as mentioned above and described below:

  • x: This parameter stores the value of left/right translation.
  • y: This parameter stores the value of up/down translation.
  • z: This parameter stores the value of forward/backward translation.

In another syntax, we can only provide the p5 vector object.

Below programs illustrate the translate() function in p5.js:

Example 1: This example uses translate() function to specify the amount to displace objects.

filter_none

edit
close

play_arrow

link
brightness_4
code

function setup() {
      
    // Create Canvas of given size
    createCanvas(580, 450);
}
  
function draw() {
      
    // Set the background color
    background(220);
      
    // Fill the color
    fill('lightgreen');
      
    // Set the border weight
    strokeWeight(5);
      
    // Create rectangle
    rect(10, 10, 400, 300);
      
    // Translate the rectangle
    translate(30, 30);
      
    // Create rectangle
    rect(10, 10, 400, 300);
      
    // Translate the rectangle
    translate(30, 30);
      
    // Create rectangle
    rect(10, 10, 400, 300);
}

chevron_right


Output:

Example 2: This example uses translate() function to specify the amount to displace objects within the display window.

filter_none

edit
close

play_arrow

link
brightness_4
code

function setup() {
      
    // Create Canvas of given size
    createCanvas(580, 450);
}
  
function draw() {
      
    // Set the background color
    background(220);
      
    for(var i=0, j=255; i<255, j>0; i++, j--) {
        fill(i, j, i);
    }
      
    // Set the stroke weight
    strokeWeight(5);
      
    // Use translate function
    translate(width / 2, height / 2);
      
    translate(p5.Vector.fromAngle(millis() / 1000, 200));
      
    // Create rectangle
    rect(10, 10, 40, 30);
}

chevron_right


Output:

Reference: https://p5js.org/reference/#/p5/translate



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.