gpt4 book ai didi

javascript - 如何更改 Canvas 上圆的 X-Y 位置

转载 作者:行者123 更新时间:2023-12-01 02:51:48 27 4
gpt4 key购买 nike

我是第一次尝试 Canvas 。创建圆圈后,我希望能够通过单击按钮来更改该圆圈中心的位置。但我不知道该怎么做。有人可以建议一种方法吗?

#button{
height: 25px;
width:125px;
border: 1px solid black;
text-align: center;
cursor: pointer;
}
<html>
<head></head>
<body>
<div id="button" onclick="changePosition()">Click here</div>
<canvas id="testCanvas" width="500px" height="500px"></canvas>

<script type="text/javascript">
var canvas = document.getElementById("testCanvas");
var a = canvas.getContext("2d");
a.fillStyle = "#b22222";
a.beginPath();
a.arc(100,100,25,0,2*Math.PI);
a.fill();

function changePosition(){
//what do I put here??

}
</script>
</body>
</html>

最佳答案

您需要重新绘制场景。创建一个重置 Canvas 然后绘制圆圈的函数

var canvas = document.getElementById("testCanvas");
var ctx = canvas.getContext("2d");
var circlePos = {
left: 100,
top: 100,
}

function renderCircle( circlePos ) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#b22222";
ctx.beginPath();
ctx.arc(circlePos.left, circlePos.top, 25, 0, 2 * Math.PI);
ctx.fill();
}

function changePosition() {
circlePos.left += 10;
if ( circlePos.left > canvas.width ) {
circlePos.left = 0;
}
renderCircle( circlePos );
}
changePosition();
#button {
height: 25px;
width: 125px;
border: 1px solid black;
text-align: center;
cursor: pointer;
}
<button onclick="changePosition()">Click here</button>
<canvas id="testCanvas" width="500" height="200"></canvas>

关于javascript - 如何更改 Canvas 上圆的 X-Y 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46917938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com