我正在寻找 javascript/HTML(最好是 ReactJS)中的“随机点运动图”实现,我可以在基于网络的实验中使用它。
基本上,点在视野(圆形 Canvas )内移动(箭头表示运动方向)。信号点(显示为实心圆圈)全部沿同一方向移动,而噪声点可以沿随机方向移动。在实际显示中,一帧中相关点和不相关点看起来是一样的;图中使用实心点和空心点只是为了解释原理。
在哪里可以找到类似的实现,用户可以使用鼠标或 slider 指定方向?或者如何在 ReactJS 中实现此任务? (对于 javascript 来说是新手,因此我们将不胜感激)。
最佳答案
我已经为您构建了简单的基于 Canvas 的运动图,您可以根据需要进行扩展。到目前为止我所做的是:
- 添加了一桶球(总共:100 个)= 50 个黑色,50 个白色
- 黑人正在走向困境
- 白色是随机移动的,它们也会从墙上反弹
- 白人以随机速度行驶
- 黑人正在匀速前进
要适应黑人方向,您可以先查看此 answer确定鼠标方向并为此修补我的 balls.push
循环。
为了能够改变球的比例,我会在页面上的某处添加input
字段并替换我的硬编码noise
变量..类似于:
<input type="text" id="t" />
并在 javascript 中选择它:
var t = document.getElementById("t");
t.addEventListener('keyup', function(ev){ /* update value */ }, false);
希望这对您的研究有所帮助,我鼓励您查看我发布的代码,因此尝试学习它并扩展它:)
;(function() {
'use strict';
var c = document.getElementById('c');
var t = document.getElementById('t');
var ctx = c.getContext('2d');
var w = c.width = window.innerWidth;
var h = c.height = window.innerHeight;
// current dots
var balls=[];
var total = 100;
var noise = 50; // here we could pick the value from user input
var bounce = -1;
for(var i=0 ; i<total ; i++){
balls.push({
x : Math.random() * w,
y : Math.random() * h,
vx : ( i < noise ) ? (Math.random() * (2.5 - 1 + 1) + 1) : 2,
vy : ( i < noise ) ? (Math.random() * (2.5 - 1 + 1) + 1) : 2,
})
}
// draw all balls each frame
function draw() {
ctx.clearRect(0, 0, w, h);
var j, dot;
for(j = 0; j < total; j++) {
dot = balls[j];
ctx.beginPath();
ctx.arc(dot.x, dot.y, 4, 0, Math.PI * 2, false);
ctx.fillStyle = (j > noise) ? "rgb(0,0,0)" : "#fff";
ctx.fill();
ctx.strokeStyle = 'black';
(j < noise) ? ctx.stroke() : '';
}
}
// movement function
function update(){
var i,dot;
for( i=0 ; i< total ; i++){
dot = balls[i];
dot.x += dot.vx;
dot.y += dot.vy;
// if ball is white, bounce it
if( i < noise){
if(dot.x > w){
dot.x = w;
dot.vx *= bounce;
}else if(dot.x <0){
dot.x = 0;
dot.vx *= bounce;
}
if(dot.y > h){
dot.y = h;
dot.vy *= bounce;
}else if(dot.y<0){
dot.y = 0;
dot.vy *= bounce;
}
// if ball is black do not bounce
} else {
if(dot.x > w){
dot.x = 0;
}else if(dot.x <0){
dot.x = w;
}
if(dot.y > h){
dot.y = 0;
}else if(dot.y<0){
dot.y = h;
}
}
}
}
// loop the animation
requestAnimationFrame(function loop() {
requestAnimationFrame(loop);
update();
draw();
});
})();
html,
body {
padding: 0;
margin: 0;
}
canvas {
display: block;
background: white;
}
<canvas id="c"></canvas>
关于javascript - JavaScript/React 中的点动任务实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47732597/