/

HTML / CSS / JavaScript Tutorial

JavaScript canvas object method: restore()

[this page | pdf | back links]

The restore() method of the JavaScript DOM object corresponding to a context applied to the HTML <canvas> element returns the context’s previously saved drawing state and attributes. Context states are stored on a stack every time the save() method is called, and returned whenever the restore() method is called. The restore() method takes no parameters.

 

For contexts generated by getContext("2d"), the state characteristics that are saved or restored appear to include:

 

-        The current transformation matrix and clipping region

-        The current values of the “Styles etc.”, “Line styles”, “Text” and “Other” properties of the context, see here

 

The  current path is not part of the drawing state (it can only be reset using the beginPath method). Neither is the bitmap that has been drawn (it is a property of the canvas itself, not the context).

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
Canvas with drawing state not saved:<br>
<canvas id="element1" width="200" height="60" style="border: 1px solid black">
Browser does not support HTML 5 canvas elements</canvas>
<br><br>
canvas with red fillStyle saved, changed to yellow and then restored to red from saved value:<br>
<canvas id="element2" width="200" height="60" style="border: 1px solid black">
Browser does not support HTML 5 canvas elements</canvas>

<script>
var x1 = document.getElementById("element1");
var c1 = x1.getContext("2d");
c1.fillStyle = "yellow";
c1.fillRect(10, 10, 180, 40);

var x2 = document.getElementById("element2");
var c2 = x2.getContext("2d");
c2.fillStyle = "red";
c2.save();
c2.fillStyle = "yellow";
c2.restore();
c2.fillRect(20, 10, 160, 40);
c2.restore();

</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvasRestore() {
  var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.estore;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile