Home > Article > Web Front-end > Can the HTML5 Canvas element be created through the Canvas constructor?
In this article, we will perform how to create HTML5 canvas element from canvas constructor. We can achieve this task by using the
Before we dive into the examples, let’s first understand the definition and usage of the
The Canvas Api can be used to draw graphics via javascript and html
Much of the focus of the Canvas API has been on 2D visual effects. The WebGL API renders hardware-accelerated 2D and 3D visual effects and uses the
Let’s look at the following example to understand the canvas constructor better
The element with a given value is returned by the getElementById() function. If the element does not exist, the getElementById() function returns null. One of the most commonly used methods in HTML DOM is getElementById().
In the example below, we use getElementId() to access the
<!DOCTYPE html> <html> <body> <canvas id="tutorial1" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas> <p>Click To Apply Canvas</p> <button onclick="mytutorial()">CLICK</button> <script> function mytutorial() { var c = document.getElementById("tutorial1"); var ctx = c.getContext("2d"); ctx.fillStyle = "#D6EAF8"; ctx.fillRect(20, 20, 150, 100); } </script> </body> </html>
When the script is executed, it accesses the
If the user clicks the button, the canvas will be applied to the web page.
HTML DOM createElement() method is used to dynamically create HTML elements using JavaScript. It constructs the element node specified with the element name as argument.
Consider the following example where we use createElement() to create a
<!DOCTYPE html> <html> <style> canvas { border: 1px solid black; } </style> <body> <button onclick="mytutorial()">CLICK</button> <p>Click To Create Canvas</p> <script> function mytutorial() { var x = document.createElement("CANVAS"); var ctx = x.getContext("2d"); ctx.fillStyle = "#ABEBC6"; ctx.fillRect(20, 20, 150, 100); document.body.appendChild(x); } </script> </body> </html>
When you run the above script, it will generate output containing the prompt "Click to create canvas" and the "Click" button.
When the user clicks the button, the createElement() method will gain access and create a canvas on the web page.
The above is the detailed content of Can the HTML5 Canvas element be created through the Canvas constructor?. For more information, please follow other related articles on the PHP Chinese website!