A hidden attribute on a <canvas> tag hides the canvas.
Although the canvas is not visible, its position on the page is maintained.
A hidden attribute on a <canvas>.
The canvas is not visible.
An invisible canvas:
<p>An invisible canvas:</p>
<canvas hidden
id="canvas" width="120" height="120" ></canvas>
<script>
( () => {
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
context.fillStyle = "lightblue";
context.fillRect(10, 10, 100, 100);
} )();
</script>
The hidden attribute hides the <canvas> element.
You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid.
A hidden <canvas> element is not visible, but it maintains its position on the page.
<canvas hidden>
<canvas hidden="hidden">
Value | Description |
---|---|
hidden | Use value 'hidden' or no value at all. |
Clicking the button toggles A hidden attribute on the <canvas> element.
<canvas id="mycanvas" width="120" height="120" ></canvas>
<br /><br />
<button onclick="toggle(this)">Hide canvas</button>
<script>
( () => {
let canvas = document.getElementById("mycanvas");
let context = canvas.getContext("2d");
context.fillStyle = "lightblue";
context.fillRect(10, 10, 100, 100);
} )();
let toggle = button => {
let canvas = document.getElementById("mycanvas");
let hidden = canvas.getAttribute("hidden");
if (hidden) {
canvas.removeAttribute("hidden");
button.innerText = "Hide canvas";
} else {
canvas.setAttribute("hidden", "hidden");
button.innerText = "Show canvas";
}
}
</script>
Initially the <canvas> element has no hidden attribute and is visible.
Clicking the button calls JavaScript which toggles A hidden attribute on the <canvas>.
Here is when hidden support started for each browser:
Chrome
|
4.0 | Jan 2010 |
Firefox
|
2.0 | Oct 2006 |
IE/Edge
|
9.0 | Mar 2011 |
Opera
|
9.0 | Jun 2006 |
Safari
|
3.1 | Mar 2008 |