Create a Canvas Element - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Canvas

Introduction

You can create a <canvas> element by using the document.createElement() method:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
canvas {/* www.  ja va  2s  .c o  m*/
    border: 1px solid black;
}
</style>
</head>
<body>

<button onclick="myFunction()">Test</button>

<p>Click the button to create a CANVAS element, with drawings (a red rectangle).</p>

<script>
function myFunction() {
    var x = document.createElement("CANVAS");
    var ctx = x.getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(20, 20, 150, 100);
    document.body.appendChild(x);
}
</script>

</body>
</html>

Related Tutorials