要使用HTML5 Canvas繪製圖形,必須先獲取2D上下文,再調(diào)用繪圖方法。 1. 在HTML中添加canvas元素並設(shè)置寬高;2. 用JavaScript通過getElementById獲取canvas元素,並調(diào)用getContext('2d')獲取2D繪圖上下文;3. 使用fillStyle設(shè)置顏色,調(diào)用fillRect繪製矩形或beginPath結(jié)合arc繪製圓形,最終實現(xiàn)圖形繪製,完整示例如文中所示,且必須先有上下文才能進(jìn)行任何繪製操作。

Creating a simple drawing with HTML5 Canvas is straightforward and only requires a few lines of HTML and JavaScript. Here's how you can draw a basic shape — like a rectangle — on a canvas.

1. Set up the Canvas Element
Start by adding a <canvas></canvas>
element to your HTML file. This is where your drawing will appear.
<canvas id="myCanvas" width="400" height="300"></canvas>
The width
and height
attributes define the drawing area. Without them, the canvas defaults to 300×150 pixels.

2. Get the Canvas Context with JavaScript
To draw on the canvas, you need to access its 2D rendering context. Use JavaScript to get the canvas and its context:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
The getContext('2d')
method returns an object that provides drawing functions.

3. Draw a Simple Shape
Now use the context to draw something. For example, here's how to draw a filled rectangle:
ctx.fillStyle = 'blue'; // Set fill color
ctx.fillRect(50, 50, 200, 100); // Draw rectangle (x, y, width, height)
This draws a blue rectangle starting at (50, 50) with a width of 200 pixels and height of 100.
Full Example: Drawing a Colored Rectangle
Here's a complete, working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Simple Canvas Drawing</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #000;"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a blue rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 200, 100);
// Optional: Add a border
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.strokeRect(50, 50, 200, 100);
</script>
</body>
</html>
This will show a blue rectangle with a black border on a white background.
Bonus: Draw a Circle
You can also draw other shapes. Here's how to draw a red circle:
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(200, 150, 50, 0, Math.PI * 2); // (x, y, radius, startAngle, endAngle)
ctx.fill();
Place this after the rectangle code to see both shapes.
That's it! You've created a simple drawing using HTML5 Canvas. From here, you can explore lines, text, images, and animations. The key steps are always:
- Add a
<canvas></canvas>
element
- Get the 2D context
- Use drawing methods like
fillRect
, arc
, beginPath
, etc.
Basically just remember: no context, no drawing.
以上是如何使用HTML5畫布創(chuàng)建簡單的圖紙?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!