Получите оповещение и получите текст внизу - PullRequest
0 голосов
/ 27 мая 2020

Я пытаюсь получить оповещение только из большого большого круга. Предупреждение не должно исходить из маленьких кружков. Как получить бдительность только из большого круга? и текст для маленького кружка должен быть внизу каждого кружка. Для меня это отображается в правом верхнем углу кружков. Может ли кто-нибудь помочь мне решить эту проблему? Заранее спасибо

var noop = function() {
  return this;
};

function UserCanceledError() {
  this.name = 'UserCanceledError';
  this.message = 'User canceled dialog';
}
UserCanceledError.prototype = Object.create(Error.prototype);

function Dialog() {
  this.setCallbacks(noop, noop);
}
Dialog.prototype.setCallbacks = function(okCallback, cancelCallback) {
  this._okCallback     = okCallback;
  return this;
};
Dialog.prototype.waitForUser = function() {
  var _this = this;
  return new Promise(function(resolve, reject) {
    _this.setCallbacks(resolve, reject);
  });
};

Dialog.prototype.show = noop;
Dialog.prototype.hide = noop;

function PromptDialog() {
  Dialog.call(this);
  this.el           = document.getElementById('dialog');
  this.messageEl    = this.el.querySelector('.message');
  this.okButton     = this.el.querySelector('button.ok');
  this.attachDomEvents();
}
PromptDialog.prototype = Object.create(Dialog.prototype);
PromptDialog.prototype.attachDomEvents = function() {
  var _this = this;
  this.okButton.addEventListener('click', function() {
    _this.hide();
    console.log('Ok clicked!!');
  });
  
};
PromptDialog.prototype.show = function(message) {
  this.messageEl.innerHTML = '' + message;
  this.el.className = '';
  return this;
};
PromptDialog.prototype.hide = function() {
  this.el.className = 'hidden';
  return this;
};


var prompt = new PromptDialog();

const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});

const drawBall = (ball, ctx) => {
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
  ctx.fillStyle = ball.collider ? "red" : ball.color;
  ctx.fill();
  ctx.closePath();
}

const updatePos = (ball, containerR) => {

  ball.x += ball.dx;
  ball.y += ball.dy;
  const dx = ball.x - containerR;
  const dy = ball.y - containerR;

  if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
    const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
    const angleToCollisionPoint = Math.atan2(-dy, dx);
    const oldAngle = Math.atan2(-ball.dy, ball.dx);
    const newAngle = 2 * angleToCollisionPoint - oldAngle;
    ball.dx = -v * Math.cos(newAngle);
    ball.dy = v * Math.sin(newAngle);
  }
}

function makeArea(domid, radius, ballsNumber) {
  const ctx = document.getElementById(domid).getContext("2d");
  const containerR = radius;
  const size = radius * 2
  ctx.canvas.width = ctx.canvas.height = size;
  ctx.globalAlpha = 1;
  
  let balls = [];
  for(var i=0 ; i<ballsNumber ; ++i) {
    const r = Math.random()*radius*0.5;
    const t = Math.random()*Math.PI*2;
    balls.push(getBall(radius + Math.cos(t)*r, radius + Math.sin(t)*r, 0.1, 0.1, 5, "Green"));
  }
  
  return {
    ctx: ctx,
    radius: radius,
    balls: balls
  }
}

const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));

const areas = [
  makeArea("Canvas", 150, 10, true),
  makeArea("Canvas1", 80, 4, false),
  makeArea("Canvas2", 80, 4, false),
  makeArea("Canvas3", 80, 4, false),
  makeArea("Canvas4", 80, 4, false)
];

function engine() {
  //console.clear(); // Clear console test messages
  mydiv.textContent =" ";
  areas.forEach((area) =>{
    const ctx = area.ctx;
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    area.balls.forEach((a, ai) => {
      a.collider = undefined;

      area.balls.forEach((b, bi) => {
        if (bi === ai) return; // Don't look at self
        if (collides(a, b)) a.collider = b; // Store the colliding B ball
      });

      if (a.collider) { // If ball has a collider:
       //mydiv.textContent = ("Alert");
       //beep();
       prompt.show('ALERT!!!!! Not Maintaining Distance')
        .waitForUser()
        .then(function(name) {
          output.innerHTML = '' + name;
        })
        .catch(function(e) {
          console.log('Unknown error', e);
        })
        .finally(function() {
          prompt.hide();
        });

        //console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
      }
      updatePos(a, area.radius);
      drawBall(a, ctx);
    });
  });
  requestAnimationFrame(engine);
}

engine();
canvas {
  background: #eee;
  margin: 0 auto;
  border-radius: 50%;
  box-shadow: 0 0 0 4px #000;

}
.row {
  display: flex;
}

.Row {
  display: flex;
  flex-direction: row;
  margin-left: 40%;
  margin-top: 8%;
  float: right;
}

#Canvas1, #Canvas2, #Canvas3, #Canvas4 {
    background: #eee;
    border-radius: 50%;
    border: solid 0px #000;
    margin: 2px;
}
<div class="Row">
    <div>
        <canvas id="Canvas"></canvas>
    </div>
    <div>
        <div class="row">
            <canvas id="Canvas1"></canvas>
              <span> xyz</span>
            <canvas id="Canvas2"></canvas>
             <span> xyz1</span>
        </div>
        
        
        <div class="row">
            <canvas id="Canvas3"></canvas>
            <span> xyz2</span>
            <canvas id="Canvas4"></canvas>
            <span>xyz3</span>
        </div>
    </div>
</div>
<div id="mydiv"></div>
<div id="dialog" class="hidden">
  <div class="message"></div>
  <div>
    <button class="ok">OK</button>
  </div>
</div>

1 Ответ

0 голосов
/ 27 мая 2020

Относительно вашего второго вопроса:

<span>s - это просто дочерние элементы .row, как и холст. Вы можете «сгруппировать» их на холсте и сделать их положение абсолютным:

/* important stuff: */
.group {
  position: relative;
}
.group span {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 5px;
  text-align: center;
}

/* only for testing: */
#canvas1 { 
  background: #eee;
  width: 100%;
  height: 100%
}
.row {
  width: 200px;
  height: 200px;
  display: flex;
}
<div class="row">
  <div class="group">
    <canvas id="canvas1"></canvas>
    <span>xyz</span>
  </div>
</div>

О предупреждении из большого круга:

Если вы расширяете forEach на все области с помощью переменной для индекса .. .

areas.forEach((area, areaindex) => {

... вы можете проверить нулевой индекс позже:

if (a.collider && areaindex == 0)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...