/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: scale()

[this page | pdf | back links]

The scale() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element scales the current drawing. It also scales future drawings and the positioning is also scaled. The parameters are scaling factors, so 1 means stay at 100% of previous size, 0.5 means adjust to 50% of previous size etc.

 

It has the following syntax with the following parameters:

 

context.scale(scalewidth,scaleheight)

 

Parameter

Required / Optional

Description

scalewidth

Required

Scaling factor applied to width

scaleheight

Required

Scale factor applied to height (

 

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.strokeStyle = "blue";
c2.strokeRect(10, 10, 40, 30);
c2.scale(3, 1.5);
c2.strokeStyle = "red";
c2.strokeRect(10, 10, 40, 30);
document.getElementById("element").appendChild(x2);
</script>

</body>
</html>

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


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


Desktop view | Switch to Mobile