【发布时间】: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