gpt4 book ai didi

javascript - 如何将元素添加到随时间变化的 Canvas 中?

转载 作者:行者123 更新时间:2023-11-27 23:48:50 25 4
gpt4 key购买 nike

每当有人点击我网站的某些部分时,我想显示一个随着时间的推移变大的圆圈。我想通过 Canvas 来做。到目前为止,我设法在访问者点击的位置添加了圆圈:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Canvas</title>
</head>
<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #cccccc;">

</canvas>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script>

/* Canvas test. */
$(function() {
var c = $("#myCanvas");
// add element that changes over time,
$(c).click(function(e) {
var ctx = this.getContext("2d");
ctx.beginPath();
ctx.arc(e.pageX,e.pageY,40,0,2*Math.PI);
ctx.stroke();
});
});

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

是否也可以让这些圆圈每 100 毫秒改变半径 1px,并在半径大于 Canvas 时消失?

没有 Canvas 也可以这样做吗?

最佳答案

Imgur

解决方案:

您必须使用requestAnimationFrame,添加元素并随时间变化,将点插入数组并绘制圆圈。

/* Canvas test. */
var circles = [];
var canvas = null;
var ctx = null;

function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);

circles.forEach(function(arg) {
var size = 100 - (new Date() - arg.time) / 10;
if (size <= 0)
return;
ctx.beginPath();
ctx.arc(arg.x, arg.y, size, 0, 2 * Math.PI);
ctx.stroke();
});

requestAnimFrame(loop);
}

$(function() {
canvas = $("#myCanvas")[0];
ctx = canvas.getContext("2d");

window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();

requestAnimFrame(loop);
});


$(function() {
var c = $("#myCanvas");
// add element that changes over time,
$(c).click(function(e) {
circles.push({
time: +new Date(),
x: e.pageX,
y: e.pageY
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #cccccc;"></canvas>

关于javascript - 如何将元素添加到随时间变化的 Canvas 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28318875/

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