Javascript translate() method

The translate function of a 2D drawing context is employed to shift the canvas and its starting point by x and y units via the translate(x,y) method.

On the other hand, when the translate method is used, it remaps the drawing position (0,0) on the canvas. This remapping affects the values in the x- and y-coordinate parameters when a method such as fillRect is invoked following the translate method.

Syntax

An illustration showcasing the syntax of the translate method is presented below:

Example

variable_canvas.translate(x, y);

Syntax explanation

  • x represents the horizontal distance by which we want to move the canvas's origin. If x is positive, the origin shifts to the left; if x is negative, it shifts to the right.
  • Y stands for the vertical distance that we wish to shift the canvas's origin by. When y is positive or negative, the origin shifts accordingly.
  • The canvas's origin (0,0) is, by default, located in the left corner of the canvas.
  • The entire coordinate system is moved by adding a translation transformation, and its new origin is located at (x,y).
  • Use of the javascript translate.

Utilizing the translate function can be very beneficial in programming. For an exercise, try creating two objects where one is a transformed version of the other using translation.

Drawing the initial item and performing a translation can be achieved. Subsequently, the second object can be rendered on the canvas.

It is necessary to calculate the updated coordinates of the second object without applying the translation transformation.

Examples

The provided examples demonstrate how to position the drawing format correctly by utilizing the translate method.

In this example, we demonstrate the fundamental usage of the translate method for moving a square on the canvas. The canvas displays a light grey background, and the square changes its position to an orange color. The square's position is adjusted using the translate method in JavaScript.

Example

<!DOCTYPE html>

<html lang = "en">

<head>

<meta charset = "UTF-8">

<meta name = "viewport" content = "width=device-width, initial-scale=1.0">

<title> JavaScript translate() method </title>

</head>

<body>

<h3> JavaScript translate() method </h3>

<canvas id = "canvas_data" height = "200" width = "300" style = "background-color:lightgrey;">

</canvas>

<script>

function draw_line() {

const canvas_var = document.querySelector('#canvas_data');

if (!canvas_var.getContext) {

return;

}

const ct_var = canvas_var.getContext('2d');

// set square's color

  ct_var.fillStyle = 'yellow';

  // set rectangle's height, width, and other dimensions

    ct_var.fillRect(100, 80, 50, 50);

    // translate

    ct_var.translate(120, 110);

    // draw the second square

    ct_var.fillStyle = 'orange';

     // set square height, width, and other dimensions

    ct_var.fillRect(0, 0, 50, 50);

ct_var.stroke();

}

draw_line();

</script>

</body>

</html>

Output

The illustration displays two squares positioned according to the specified style and location.

Illustrative Example 2: Below is a demonstration of utilizing the translate method multiple times to create multiple squares on the canvas. This approach involves employing various methods to present distinct squares according to the user's specifications.

Example

<!DOCTYPE html>

<html lang = "en">

<head>

<meta charset = "UTF-8">

<meta name = "viewport" content = "width=device-width, initial-scale=1.0">

<title> JavaScript translate() method </title>

</head>

<body>

<h3> Multiple JavaScript translate() method </h3>

<canvas id = "canvas_data" height = "200" width = "300" style = "background-color:lightgrey;">

</canvas>

<script>

function draw_line() {

const canvas_var = document.querySelector('#canvas_data');

if (!canvas_var.getContext) {

return;

}

const ct_var = canvas_var.getContext('2d');

//translate yellow square

ct_var.translate(60, 5);

// set square's color

  ct_var.fillStyle = 'yellow'; 

  // set rectangle's height, width, and other dimensions

    ct_var.fillRect(100, 80, 50, 50);

    //translate the orange cube

   ct_var.translate(20, 30);

    // draw the second square

    ct_var.fillStyle = 'orange';

     // set square height, width, and other dimensions

    ct_var.fillRect(0, 50, 50, 50);

     //translate the black cube

     ct_var.translate(50, 20);

// draw the second square

    ct_var.fillStyle = 'black';

     // set square height, width and other dimension

    ct_var.fillRect(0, 1, 50, 50);

}

draw_line();

</script>

</body>

</html>

Output

The image displays numerous squares arranged according to the specified style and placement.

Illustrative Example 3: Below is a demonstration showcasing the utilization of the translate method multiple times with negative values as inputs to generate multiple squares. In this scenario, various squares are created through multiple invocations of the translate method, employing both positive and negative values, as well as minimum values, to render them in the desired format for the user.

Example

<!DOCTYPE html>

<html lang = "en">

<head>

<meta charset = "UTF-8">

<meta name = "viewport" content = "width=device-width, initial-scale=1.0">

<title> JavaScript translate() method </title>

</head>

<body>

<h3> JavaScript translate() method with negative values </h3>

<canvas id = "canvas_data" height = "200" width = "300" style = "background-color:lightgrey;">

</canvas>

<script>

function draw_line() {

const canvas_var = document.querySelector('#canvas_data');

if (!canvas_var.getContext) {

return;

}

const ct_var = canvas_var.getContext('2d');

// set square's color

  ct_var.fillStyle = 'yellow'; 

  // set rectangle's height, width, and other dimensions

    ct_var.fillRect(100, 80, 50, 50);

    //translate the square

ct_var.translate(-60, -15);

    ct_var.fillStyle = 'orange';

     // set square height, width, and other dimensions

    ct_var.fillRect(200, 150, 55, 55);

// draw the second square

    ct_var.fillStyle = 'black';

     // set square height, width, and other dimensions

    ct_var.fillRect(200, 61, 50, 50);  

}

draw_line();

</script>

</body>

</html>

Output

The image displays several squares arranged according to the specified style and location.

Illustrative Instance 4: Below is a demonstration showcasing the utilization of the translate method multiple times for the clock shape. In this scenario, various methods are employed to exhibit the shape by utilizing values.

Example

<!DOCTYPE html>

<html lang = "en">

<head>

<meta charset = "UTF-8">

<meta name = "viewport" content = "width=device-width, initial-scale = 1.0">

<title> JavaScript translate() method </title>

</head>

<body>

<h3> JavaScript translate() method with positive values

</h3>

<h4> Display Clock Position using Canvas

</h4>

<canvas id = "canvas_data" height = "200" width = "300" style = "background-color:lightgrey;">

</canvas>

<script>

function draw_line() {

const canvas_var =document.querySelector('#canvas_data');

if (!canvas_var.getContext) {

return;

}

if (canvas_var.getContext) {

    const ct_var = canvas_var.getContext('2d');

    ct_var.beginPath();

    const centerX_value = canvas_var.width / 3,

        centerY_value = canvas_var.height / 2.5;

    // draw the circle

    ct_var.arc(centerX_value, centerY_value, 74, 0, 3 * Math.PI, false);

    // translate to center

    ct_var.translate(centerX_value, centerY_value);

 //ct_var.translate(60, 1);

    // draw the hour hand

    ct_var.moveTo(0, 0);

   ct_var.lineTo(-30, -20);

    // draw the minute hand

   ct_var.moveTo(0, 0);

    ct_var.lineTo(0, -55);

  ct_var.stroke();

}

}

draw_line();

</script>

</body>

</html>

Output

The illustration displays several squares arranged according to the specified style and location.

Illustrative Example 5: Demonstrating the application of the translate method with varying positive and negative values to manipulate the position of a clock shape. In this scenario, a unified method is leveraged to showcase different line positions by adjusting the values to render the desired shape, transforming a vertical line into a diagonal representation.

Example

<!DOCTYPE html>

<html lang = "en">

<head>

<meta charset = "UTF-8">

<meta name = "viewport" content = "width=device-width, initial-scale=1.0">

<title> JavaScript translate() method </title>

</head>

<body>

<h3> JavaScript translate() method with positive and negative values </h3>

<h4>

Display line with position using Canvas

</h4>

<canvas id = "canvas_data" height = "150" width = "200" style = "background-color:#F8F8FF;">

</canvas>

<script>

function draw_line() {

const canvas_var = document.querySelector('#canvas_data');

if (!canvas_var.getContext) {

return;

}

if (canvas_var.getContext) {

const ct_var = canvas_var.getContext('2d');

// set line stroke, line color, and line width

ct_var.strokeStyle = 'orange';

ct_var.lineWidth = 5;

// draw a black line horizontally

ct_var.beginPath();

//set horizontal line and its movement

ct_var.moveTo(100, 10);

//use translate method on vertical line

ct_var.translate(-60, 15);

//Set the line size on the canvas

ct_var.lineTo(100, 100);

ct_var.stroke();

}

}

draw_line();

</script>

</body>

</html>

Output

The image displays several squares arranged according to the specified style and location.

Illustrative Example 6: Demonstrated below are diverse lines rendered on the canvas by utilizing the parameters within the JavaScript translate function. It is possible to employ numerous input parameters to create multiple lines through a solitary method. The input method can accommodate 0, null, as well as numerical values.

Example

<!DOCTYPE html>

<html lang = "en">

<head>

<meta charset = "UTF-8">

<meta name = "viewport" content = "width=device-width, initial-scale=1.0">

<title> JavaScript translate() method </title>

</head>

<body>

<h3> JavaScript translate() method with positive and negative values </h3>

<h4>



Display multiple lines with position using Canvas

</h4>

<canvas id = "canvas_data" height = "150" width = "200" style = "background-color: black;">

</canvas>

<script>

function drawLine_function(ctx_var, x1, y1, x2,y2, stroke, width, trans_x, trans_y) {

        //Start a new path on the line

        ctx_var.beginPath();

        // Use the cursor from the start point of the line

        ctx_var.moveTo(x1, y1);

	//use translate method on lines

ctx_var.translate(trans_x, trans_y);

        //Draw a line from the start cursor position to the given coordination

        ctx_var.lineTo(x2, y2);

        // set color of the line

        ctx_var.strokeStyle = stroke;

        // set line Widht 

        ctx_var.lineWidth = width;

        // add a stroke() method of the line to the end function 

        ctx_var.stroke();

      }

      let canvas_var = document.getElementById('canvas_data'),

          ctx_var = canvas_var.getContext('2d');

      drawLine_function(ctx_var, 10, 100, 350, 300, 'Aqua', 4, 20, -50);

      drawLine_function(ctx_var, 10, 100, 600, 10, 'pink', 5, -5, -10);

       drawLine_function(ctx_var, 10, 100, 100, 100, 'yellow', 6, 5, 30);

       drawLine_function(ctx_var, 10, 100, 50, 200, 'orange', 8, 22, -20);

</script>

</body>

</html>

Output

The illustration displays various lines with varying thickness and positions on the canvas.

Conclusion

The translate function illustrates specific shapes and layouts by utilizing various x and y coordinates as input data. It is beneficial for visualizing maps, charts, and other two-dimensional formations.

Input Required

This code uses input(). Please provide values below: