【问题标题】:How to draw a circle with on button click with javascript如何用javascript点击按钮绘制一个圆圈
【发布时间】:2021-11-11 15:36:46
【问题描述】:

我今天决定尝试 JavaScript 图形,我设法找到了一个名为 draw() 的函数,它应该从画布对象中获取绘图上下文,并从画布对象中调用一些绘图方法来绘制图形。

逻辑

我硬编码了一个 canvas html 标签并给它一个id.. 从我的 JavaScript draw() 函数中访问了画布对象,然后访问了相同的画布二维绘图上下文并调用了在二维绘图上下文对象中找到的绘图方法。

期待

当我单击绘图按钮时,我希望我的代码在 body 标记的画布上绘制一个黑色圆圈,但 draw() 函数似乎有问题,请帮助

function draw() {
  //get the drawing canvas
  let canvas = document.getElementById("mycanvas");
  //check if the context returns true
  if (canvas.getContext) {
    let ctx = canvas.getContext('2d');
    //get the co ordinates
    let X = canvas.width / 2;
    let Y = canvas.height / 2;
    //define the radius
    let R = 45;
    //begin drawing the circle
    ctx.beginPath();
    ctx.arc(X, Y, R, O, 2 * Math.PI, false);
    //set the thickness of the draw print
    ctx.lineWidth = 3;
    //set the color of the draw print
    ctx.strokeStyle = "#111";
    //start drawing the object
    ctx.stroke();
  }
}
canvas {
  height: 300px;
  width: 300px;
}

.mybutton {
  background: #964b00;
  color: #fff;
  font-size: 22px;
  padding: 5px;
  font-family: serif;
  text-align: center;
}
<!--declare a canvas object we will use to draw the circle-->
<center><canvas id="mycanvas"></canvas></center>
<center><button class="mybutton" onclick="draw()">mybutton</button></center>

【问题讨论】:

  • 你的画布画了吗?
  • 查看浏览器控制台中的错误。未定义 O 变量。
  • ctx.arc(X, Y, R, O, 2 * Math.PI, false);在您的代码中,我可以看到您没有提及/声明“O”变量的值。
  • 请将其设为 0(零)。
  • 所以这是一个错字,好的,谢谢,更正

标签: javascript html canvas


【解决方案1】:

您为 sAngle 参数传递了一个未定义的变量 (O)。

我假设你的意思是传递 0 以使其工作(弧度中 0 位于圆弧的第三点钟位置)

function draw() {
  //get the drawing canvas
  let canvas = document.getElementById("mycanvas");
  //check if the context returns true
  if (canvas.getContext) {
    let ctx = canvas.getContext('2d');
    //get the co ordinates
    let X = canvas.width / 2;
    let Y = canvas.height / 2;
    //define the radius
    let R = 45;
    //begin drawing the circle
    ctx.beginPath();
    ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
    //set the thickness of the draw print
    ctx.lineWidth = 3;
    //set the color of the draw print
    ctx.strokeStyle = "#111";
    //start drawing the object
    ctx.stroke();
  }
}
canvas {
  height: 300px;
  width: 300px;
}

.mybutton {
  background: #964b00;
  color: #fff;
  font-size: 22px;
  padding: 5px;
  font-family: serif;
  text-align: center;
}
<!--declare a canvas object we will use to draw the circle-->
<center><canvas id="mycanvas"></canvas></center>
<center><button class="mybutton" onclick="draw()">mybutton</button></center>

【讨论】:

    【解决方案2】:

    请定义会导致错误的“O”变量。在draw() 中添加let O =50 你会得到结果

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2021-06-09
    • 2014-09-25
    • 2023-03-03
    • 2022-01-15
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多