Canvas code can be written inside the
tag of an HTML file, usually as part of the HTML document. The core of the Canvas code is to obtain and operate the context of the Canvas element, through document.getElementById('myCanvas' ) to obtain a reference to the Canvas element, and then use getContext('2d') to obtain the 2D drawing context.
# Operating system for this tutorial: Windows 10 system, Dell G3 computer.
Canvas code can be written inside the
tag of an HTML file, usually as part of the HTML document.The following is the basic format of Canvas code:
<!DOCTYPE html> <html> <head> <title>Canvas示例</title> <style> /* 这里可以定义样式 */ </style> <script> window.onload = function() { // 在这里编写Canvas代码 const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // 绘制操作代码... } </script> </head> <body> <h1>Canvas示例</h1> <canvas id="myCanvas" width="500" height="300"></canvas> <!-- 其他HTML内容... --> </body> </html>
In the above example, we wrote the Canvas code in the window.onload event handler inside the <script> tag. This is to ensure that the Canvas code is executed after the Canvas element is loaded to avoid errors where the Canvas element cannot be found. You can also place the Canvas code in a custom JavaScript file and import it using <script src="script.js"></script>.
The core of the Canvas code is to obtain and operate the context of the Canvas element. Get the reference to the Canvas element through document.getElementById('myCanvas'), and then use getContext('2d') to get the 2D drawing context. Next, you can use the methods and properties provided by the context to perform drawing operations.
The following is a simple Canvas instance that draws a red rectangle:
<!DOCTYPE html> <html> <head> <title>Canvas示例</title> <style> /* 这里可以定义样式 */ </style> <script> window.onload = function() { const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'red'; // 设置填充颜色为红色 ctx.fillRect(50, 50, 200, 100); // 绘制矩形 } </script> </head> <body> <h1>Canvas示例</h1> <canvas id="myCanvas" width="500" height="300"></canvas> <!-- 其他HTML内容... --> </body> </html>
In the above example, we use the Canvas context object ctx to set the fill color to red and call fillRect( ) method draws a rectangle. The coordinates of the upper left corner of the rectangle are (50, 50), the width is 200, and the height is 100. You can specify different parameter values in the fillRect() method to achieve other shapes and drawing effects.
The above is the detailed content of Where to write canvas code. For more information, please follow other related articles on the PHP Chinese website!