要繪製簡單形狀,需先設(shè)置canvas元素並獲取2D上下文,1. 在HTML中添加帶id、width和height屬性的

Drawing a simple shape on an HTML5 canvas is straightforward once you set up the canvas element and get its drawing context. Here's how you can do it step by step.

1. Set up the <canvas></canvas>
element
First, add a <canvas></canvas>
tag in your HTML. Give it an id
so you can easily reference it in JavaScript, and set its width
and height
attributes:
<canvas id="myCanvas" width="200" height="200"></canvas>
? Note: Use the width
and height
attributes directly on the canvas, not CSS, to avoid distortion.

2. Get the 2D drawing context
In JavaScript, get the canvas element and its 2D rendering context:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
The ctx
object is what you'll use to draw shapes, lines, and colors.

3. Draw a simple rectangle
Let's draw a solid red rectangle:
ctx.fillStyle = 'red'; // Set fill color
ctx.fillRect(10, 10, 150, 100); // (x, y, width, height)
This draws a 150×100 pixel red rectangle starting at coordinates (10, 10) from the top-left corner of the canvas.
Full example
Here's a complete working example:
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 100, 50);
</script>
This draws a blue rectangle.
Other basic shapes
Stroke (outline) rectangle :
ctx.strokeStyle = 'green';
ctx.strokeRect(10, 10, 100, 50);
Clear a rectangle :
ctx.clearRect(0, 0, canvas.width, canvas.height); // Useful for animations
Custom path (like a triangle) :
ctx.beginPath();
ctx.moveTo(50, 10); // Start point
ctx.lineTo(100, 100); // Line to bottom-right
ctx.lineTo(0, 100); // Line to bottom-left
ctx.closePath(); // Back to start
ctx.fillStyle = 'purple';
ctx.fill();
Basically, you just need a canvas, a context, and a few method calls. The key is starting with getContext('2d')
and then using drawing methods like fillRect
, strokeRect
, or path commands.
以上是您如何在HTML5畫布上繪製簡單的形狀?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!