使用canvas畫出一個矩形

王铁柱6發表於2024-11-25
<!DOCTYPE html>
<html>
<head>
<title>Canvas Rectangle</title>
</head>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red"; // Fill color
ctx.fillRect(20, 20, 150, 50); // x, y, width, height
</script>

</body>
</html>

This code creates a canvas element with a black border. Then, it gets the 2D rendering context and draws a red rectangle:

  • fillStyle = "red": Sets the fill color to red. You can use any valid CSS color here (e.g., hex codes, color names, rgb values).
  • fillRect(20, 20, 150, 50): Draws a filled rectangle.
    • 20: x-coordinate of the top-left corner.
    • 20: y-coordinate of the top-left corner.
    • 150: Width of the rectangle.
    • 50: Height of the rectangle.

If you want just the outline of a rectangle, use strokeRect() instead of fillRect():

ctx.strokeStyle = "blue"; // Outline color
ctx.lineWidth = 2;       // Line thickness
ctx.strokeRect(20, 20, 150, 50);

This will draw a blue rectangle outline with a line thickness of 2 pixels. You can adjust the strokeStyle and lineWidth properties as needed.

相關文章