迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

使用 JavaScript 在 HTML5 Canvas 中绘制圆

作者:迹忆客 最近更新:2024/03/19 浏览次数:

图形是任何 Web 应用程序的重要组成部分。HTML 提供了两种创建图形的方法,第一种是 canvas,另一种是 SVG。在今天的帖子中,我们将学习如何使用画布和 JavaScript 在 HTML 中创建图形,特别是圆(二维)。


在 HTML 中使用 JavaScript 通过 canvas 绘制圆圈

Canvas 是 HTML 提供的默认元素,用于在 Web 应用程序上绘制图形。它只不过是页面上没有边框和内容的矩形区域。用户可以使用这个矩形区域来绘制图形。

在画布中呈现的图形不同于常规的 HTML 和 CSS 样式。整个画布及其包含的所有图形都被视为单个 dom 元素。

HTML 中 canvas 的方法

arc 的语法

context.arc(
    $centerX, $centerY, $radius, $startAngle, $endAngle, $counterclockwise);

参数

  • $centerX:这是一个强制性参数,用于指定 X 或圆的水平坐标/中心点。
  • $centerY:它是一个强制性参数,用于指定圆的 Y 或垂直坐标/中心点。
  • $radius:这是一个强制参数,用于指定圆的半径。这必须是积极的。
  • $startAngle:这是一个强制性参数,用于指定从正 x 轴测量的弧度的弧的起始角度。
  • $endAngle:这是一个强制性参数,用于指定从正 x 轴测量的弧度的弧度终止角度。例如,2 * Math.PI 表示一个完整的圆圈。
  • 逆时针:这是一个可选参数,指定一个布尔值,指示如何顺时针或逆时针绘制圆。默认值为 false

使用 JavaScript Canvas 绘制圆的步骤

  • 获取 Canvas 的上下文。
  • 声明 X、Y 点和半径。
  • 设置线条的颜色和宽度。
  • 画圆圈。

示例代码:

<canvas id="myCanvas" width="500" height="200"></canvas>

<script>
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 50;

context.beginPath();
context.fillStyle = '#0077aa';
context.strokeStyle = '#0077aa47';
context.lineWidth = 2;

context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fill();
context.stroke();
</script> 

输出:

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便