/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: clip()

[this page | pdf | back links]

The clip() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element clips a region from canvas. Once a region is clipped, all future drawing is limited to the clipped region, although if you save the region before clipping it can then be restored using the restore() method.

 

It has the following syntax with no parameters.

 

context.clip()

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span>

<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "100");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");

c2.rect(10, 10, 180, 80);
c2.stroke();
c2.clip();

c2.fillStyle = "blue";
c2.fillRect(0, 0, 50, 50);
document.getElementById("element").appendChild(x2);
</script>

</body>
</html>

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


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


Desktop view | Switch to Mobile