Display a text on canvas for only X seconds

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
MarPlo
Posts: 186

Display a text on canvas for only X seconds

I have written a code that adds a text in canvas on clicking a button.
And i want to display this text for lets say 2 seconds. How can I make the text in canvas disappear after 2 seconds?
This is the code.

Code: Select all

<canvas id="canvas" height="250" width="350"></canvas>
<button id="show_txt">Show text</button>

<script>
var cav = document.getElementById('canvas');  // get canvas element
var ctx = cav.getContext("2d");

// write text with gradient in canvas
function write() {
  ctx.font = "30px Verdana";

  // Create gradient
  var gradient = ctx.createLinearGradient(0,0,cav.width,0);
  gradient.addColorStop("0","magenta");
  gradient.addColorStop("0.5","blue");
  gradient.addColorStop("1.0","red");

  // Fill with gradient
  ctx.fillStyle = gradient;
  ctx.fillText("Big smile!",10,90);
}

// register click event on the #show_txt button to call write()
document.getElementById('show_txt').addEventListener('click', function(){ write();});
</script>

Admin Posts: 805
You have to use setTimeout() to call a function, after a given time, that clears the canvas content.
Here's a simple demo for writing and clearing text in canvas in 2 seconds (using your code):

Code: Select all

<canvas id="canvas" height="250" width="350"></canvas>
<button id="show_txt">Show text</button>

<script>
var cav = document.getElementById('canvas');  // get canvas element
var ctx = cav.getContext("2d");

// write text with gradient in canvas
function write() {
  ctx.font = "30px Verdana";

  // Create gradient
  var gradient = ctx.createLinearGradient(0,0,cav.width,0);
  gradient.addColorStop("0","magenta");
  gradient.addColorStop("0.5","blue");
  gradient.addColorStop("1.0","red");

  // Fill with gradient
  ctx.fillStyle = gradient;
  ctx.fillText("Big smile!",10,90);
}

// clear canvas
function clear(){
  ctx.clearRect(0,0,cav.width,cav.height);
}

// call write() function, and clear() after the received t milliseconds
function start(t) {
  write();
  setTimeout(function(){ clear();}, t);
}

// register click event on the #show_txt button to call start()
document.getElementById('show_txt').addEventListener('click', function(){ start(2000);});
</script>

Similar Topics