How to scroll text from left to right in canvas?

by elisha_langworth , in category: Javascript , 4 months ago

How to scroll text from left to right in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 4 months ago

@elisha_langworth 

To scroll text from left to right in a canvas element in HTML5, you can use the requestAnimationFrame method along with the getContext method to draw and update the text position. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
  <title>Scrolling Text</title>
</head>
<body>

<canvas id="canvas" width="400" height="200"></canvas>

<script>
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');
  
  let text = 'Scrolling Text';
  let xPos = canvas.width;

  function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    ctx.font = '20px Arial';
    ctx.fillText(text, xPos, 50);
    
    xPos--;
    if (xPos < -ctx.measureText(text).width) {
      xPos = canvas.width;
    }
    
    requestAnimationFrame(draw);
  }
  
  draw();
</script>

</body>
</html>


In this example, a canvas element is created with a width of 400px and a height of 200px. The draw function is called recursively using requestAnimationFrame to continuously draw the text at a decrementing x position (from right to left). When the text reaches the left edge of the canvas, its x position is reset to the canvas width to make it scroll continuously.


Feel free to modify the font style, text content, Canvas dimensions, or animation speed as needed.