請使用canvas畫一個橢圓

王铁柱6發表於2024-12-09
<!DOCTYPE html>
<html>
<head>
<title>Canvas Ellipse</title>
</head>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// Draw an ellipse
ctx.beginPath();
ctx.ellipse(150, 75, 50, 30, 0, 0, 2 * Math.PI); // x, y, radiusX, radiusY, rotation, startAngle, endAngle
ctx.stroke();


// Example with fill and different color
ctx.beginPath();
ctx.ellipse(100, 75, 40, 20, Math.PI / 4, 0, 2 * Math.PI); // Rotated ellipse
ctx.fillStyle = "red";
ctx.fill();


// Example with a partial ellipse (arc)
ctx.beginPath();
ctx.ellipse(220, 75, 30, 40, 0, Math.PI/2 , 3*Math.PI/2); // Half ellipse, downwards
ctx.strokeStyle = "blue";
ctx.lineWidth = 3;  // Set line thickness
ctx.stroke();



</script>

</body>
</html>

This code creates an HTML5 canvas and draws three ellipses:

  1. A simple black ellipse: Centered at (150, 75) with horizontal radius 50 and vertical radius 30.
  2. A filled red rotated ellipse: Centered at (100, 75), rotated by 45 degrees (Math.PI / 4 radians), with horizontal radius 40 and vertical radius 20.
  3. A blue half-ellipse arc: Centered at (220,75) with horizontal radius 30 and vertical radius 40. It draws the bottom half of the ellipse using Math.PI/2 as the start angle and 3*Math.PI/2 as the end angle. It also demonstrates setting the line thickness.

This provides a few examples of how to use the ellipse() method with different parameters and styling options. Remember to include this code within the <body> tags of your HTML file. You can adjust the parameters to create ellipses with different sizes, positions, rotations, and colors.

相關文章