我正在寻找一个javascript / HTML(最好是在ReactJS中)的“随机点运动图”实现,我可以在基于网络的实验中使用它。
基本上,在视野(圆形画布)内移动的点(箭头指示运动方向)。信号点(显示为实心圆圈)都沿相同方向移动,而噪声点可以随机方向移动。在实际显示中,帧中的相关和不相关点看起来是相同的;填充和打开的点在图中仅用于解释原理。
我在哪里可以找到这样的实现,用户可以使用鼠标或滑块指定方向?或者如何在ReactJS中实现此任务? (javascript新手,所以提示将受到高度赞赏)。
我建立了你简单的基于canvas
的运动图,你应该扩展到你的需要。到目前为止我所做的是:
为了适应黑人的方向你可以从这个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>