The clearCanvas() function presented in this page can be used to clear propely the drawing and text contexts from canvas.
// function to clear the canvas ( https://coursesweb.net/ )
// cnv = the object with the canvas element
function clearCanvas(cnv) {
var ctx = cnv.getContext('2d'); // gets reference to canvas context
ctx.beginPath(); // clear existing drawing paths
ctx.save(); // store the current transformation matrix
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, cnv.width, cnv.height);
ctx.restore(); // restore the transform
}
- This function is useful when you want to remove all the canvas context to can add new drawings and texts on an empty canvas.
• Here is an example, when a "Set Nr" button is clicked, a random number between 1 and 100 is displayed in canvas. A "Clear" button will clear the canvas context, so to not display the numbers one over the other; that will happen if you click the "Set Nr" button again (see the comments in code).
<h4>Canvas</h4><canvas width="200" height="100" id="cnv1"></canvas><br/>
<button id="clear_cnv">Clear</button> - <button id="setnr_cnv">Set Nr</button>
<script type="text/javascript">
// <![CDATA[
// function to clear the canvas ( https://coursesweb.net/ )
// cnv = the object with the canvas element
function clearCanvas(cnv) {
var ctx = cnv.getContext('2d'); // gets reference to canvas context
ctx.beginPath(); // clear existing drawing paths
ctx.save(); // store the current transformation matrix
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, cnv.width, cnv.height);
ctx.restore(); // restore the transform
}
// sets and adds a random number in canvas
// cnv = the object with the canvas element
function addNrCnv(cnv) {
// gets a random number between 1 and 100
var nr = Math.floor(Math.random() * 100 + 1);
var ctx = cnv.getContext('2d'); // gets reference to canvas context
// create text with the number in canvas (sets text color, font type and size)
ctx.fillStyle = '#00f';
ctx.font = 'italic 38px sans-serif';
ctx.fillText(nr, 80, 64);
}
// get a reference to the <canvas> tag
var cnv1 = document.getElementById('cnv1');
// register onclick event for #clear_cnv button to call the clearCanvas()
document.getElementById('clear_cnv').onclick = function() { clearCanvas(cnv1); }
// register onclick event for #setnr_cnv button to call the addNrCnv()
document.getElementById('setnr_cnv').onclick = function() { addNrCnv(cnv1); }
// ]]>
</script>
- Demo (Click "Set Nr" to add a random number, click "Clear" to clear the canvas):