5

Вопрос инициирован вопросом и ответом на него, в котором реализована логика взаимодействия пешеходов с сигналами светофора:

Пешеходы:

  • стоят у зебры, когда: горит желтый или красный свет
  • переходят дорогу только на зелёный свет светофора

Автомобили

  • пересекают пешеходный переход на зеленый свет
  • стоят у перехода на красный свет светофора

введите сюда описание изображения

Так как в данном приложении не видно, какой сигнал горит на светофоре для машин со стороны дороги, то условие можно несколько упростить: Пешеходы идут на зеленый свет со стороны пешеходного перехода и стоят на красный свет. Машины начинают движение на красный свет со стороны пешеходного перехода, так как для них горит зеленый свет со стороны дороги.

Условие пересечения людьми пешеходного перехода на зеленый свет реализовано в приложении. Загорание зеленого разрешающего сигнала для машин наступает после загорания красного цвета для пешеходов:

168 строка в редакторе

<animate id="bigRed" attributeName="r" begin="startRed.begin" dur="0.1s" to="28" fill="freeze" /> 
     <animate id="smallRed" attributeName="r" begin="bigRed.end+5s" dur="0.1s" to="20" fill="freeze" /> 

Но рассчитать, когда машина появится перед светофором невозможно. Так как её движение по трассе происходит при скроллинге. (крутите колесико мышки и передвигайте машину)
Но она должна остановиться (скроллинг перестанет работать) при одновременном срабатывании двух условий:

  1. При достижении зоны пешеходного перехода, в интервале от 10px - 50px до зебры
  2. и при этом для пешеходов горит зелёный свет

Другими словами, если машина находится далеко от пешеходного перехода, то она может двигаться при любом сигнале светофора для пешеходов и останавливаться у зебры при красном свете со стороны дороги (для пешеходов горит зелёный)

введите сюда описание изображения

В smil SVG невозможно управлять анимацией при совокупности двух условий (место расположения автомобиля - у зебры и сигнал светофора)

Если задать только одно условие - красный свет на переходе, то машина будет останавливаться в любом месте трассы при срабатывании красного сигнала светофора.

Исходный код приложения с реализованной логикой пересечения пешеходами дороги на зелёный цвет.

Крутите колёсико для передвижения машины (не давите людей)

// Первоначально установить автомобиль
MoveScroll();
function MoveScroll() {
  var scrollY = window.scrollY || window.pageYOffset;
  var maxScrollY = document.documentElement.scrollHeight - window.innerHeight;
  var path = document.getElementById("mPath");
  // Рассчитать расстояние по пути, на котором машина должна быть для текущего количества прокрутки
  var pathLen = path.getTotalLength();
  var dist = pathLen * scrollY / maxScrollY;
  var pos = path.getPointAtLength(dist);
  // Вычислить положение немного впереди машины (или позади, если мы в конце), чтобы мы могли рассчитать угол автомобиля.
  if (dist + 1 <= pathLen) {
    var posAhead = path.getPointAtLength(dist + 1);
    var angle = Math.atan2(posAhead.y - pos.y, posAhead.x - pos.x);
  } else {
    var posBehind = path.getPointAtLength(dist - 1);
    var angle = Math.atan2(pos.y - posBehind.y, pos.x - posBehind.x);
  }
  // Поместите автомобиль в "pos", повернутый на "angle".
  var car = document.getElementById("car");
  car.setAttribute("transform", "translate(" + pos.x + "," + pos.y + ") rotate(" + rad2deg(angle) + ")");
}

function rad2deg(rad) {
  return 180 * rad / Math.PI;
}

// Передвигать автомобиль всякий раз, когда есть событие прокрутки
window.addEventListener("scroll", MoveScroll);
<!-- https://ru.stackoverflow.com/q/1278377/28748 -->
<style>
body {
  min-height: 30000px;
}
.container {
width:100vw;
height:100vw;
}
svg {
  position: fixed;
}
</style>
<div class="container">
<svg id="svg1" viewBox="0 80 1840 1035" preserveAspectRatio="xMinYMin meet">
<defs>

   <path id="walk1"
   d="m343 268 34-10 50-9-33-86 22-14 7-21 8-3 13 18 34-25 47 65 22-19"  />
  <g id="Man" transform="translate(0,0) scale(1,-1)">
    <path   fill="none">
         <animate
          attributeName="d"
          begin="0.1s"
          dur="0.3s"
          repeatCount="indefinite"
          values="M-3,0 0,10 3,0 M0,10 0,16 l 4,-5 M0,16 l-4,-5 M0,16 c4,4 -4,4 0,0;
                  M 0,0 0,10 0,0 M0,10 0,16 l 0,-5 M0,16 l 0,-5 M0,16 c4,4 -4,4 0,0;
                  M-3,0 0,10 3,0 M0,10 0,16 l 4,-5 M0,16 l-4,-5 M0,16 c4,4 -4,4 0,0"/>
    </path> 
      </g>  
        <!-- Трасса в школу через пешеходный переход  -->
 <path id="child"  fill="none" stroke="none" d="m328 893 1-212M344 864" /> 
       <!-- Трасса в палатку через пешеходный переход  -->
   <path id="home1"  fill="none" stroke="none" d="m 344.35582,863.69183 c 0,0 -34.63139,-111.56426 0,-145.53606 29.52729,-28.96492 84.99455,-11.19516 124.06352,2.38584 15.72518,5.46632 24.12207,24.52029 39.76395,30.2206 78.91988,28.76045 173.36704,37.53827 258.46569,18.29141" /> 
    <path id="child2"  fill="none" stroke="none" d="m309 874c0 0-13-111 2-157 2-6 14 0 17-5 6-8 1-30 1-30" />  
    <!-- Трасса2 из палатки через пешеходный переход  -->
    <path id="home2" d="m 876.39749,779.39226 c 0,0 -307.5863,30.55405 -455.69489,-3.18112 -25.43694,-5.79386 -49.02287,-47.7976 -70.77983,-33.40172 -33.85116,22.39822 4.77167,121.67769 4.77167,121.67769" style="fill:none;stroke-width:2;stroke:#e02e2e"/>  
     <!-- Трасса из школы через пешеходный переход     -->
      <path id="back" d="m329 682c0 0-23 32-25 41-13 54 14 143 14 143" style="fill:none;stroke-width:2;stroke:#da3434"/>
    
  </defs>
  <!--Карта-->
  <g id="map" x="0" y="0" transform="scale(1) translate(0,0)">
    <image href="https://i.imgur.com/uTmJYO7.png">
    </image>
  </g>

 

<!--Путь-->
<path id="mPath" fill="none" stroke="none" stroke-width="1px" d="M-99.9 458.3C405 455.9 909.9 453.5 1168.1 451.5c258.3-2 269.8-3.7 284-9 14.2-5.3 31-14.2 44.5-25.7 13.5-11.5 24-25.7 30.9-40 6.9-14.3 10.3-28.6 12-52.9 1.7-24.3 1.7-59-0.7-82.6-2.4-23.5-7.2-36.5-14.1-48.6-6.8-12.1-15.9-23.8-27.6-34.1-11.7-10.3-26-19.2-41-25.4-15.1-6.2-30.4-9.6-69.2-10.9-38.8-1.4-100.8-0.8-138.2 3.2-37.4 4-50.2 11.4-61.6 19.2-11.5 7.9-21.6 16.3-31 28.1-9.4 11.9-17.9 27.2-23.1 42.3-5.2 15.1-7 29.8-6.3 113.4 0.7 83.6 3.9 235.9 2.4 318.2-1.5 82.3-7.7 94.4-13.2 104.4-5.5 9.9-10.6 17.8-19.2 27.4-8.6 9.6-20.7 20.9-34.1 29.3-13.4 8.4-27.9 13.8-167.6 16.5-139.7 2.7-404.5 2.7-542.3 1.2-137.8-1.5-149-4.5-161.3-10.4-12.4-5.9-26.1-14.7-37.6-26.8-11.5-12.2-20.6-27.7-26.5-41.9-5.9-14.1-8.5-26.9-9.7-101.5-1.2-74.6-1-211 0.4-283.5 1.4-72.5 4-81.1 8.9-91.2 4.9-10.2 12.1-21.9 21.1-32.7 9.1-10.8 20-20.5 31.3-27.6 11.3-7.1 22.8-11.5 34.8-14.2 12-2.8 24.7-4 94.9-4.5 70.2-0.5 198-0.3 264.3 0.6 66.3 0.9 70.7 2.5 77.6 5 6.9 2.5 16.1 5.9 25.9 12 9.9 6.1 20.4 14.9 29.5 25 9.1 10.2 16.7 21.7 22 33.8 5.4 12.1 8.6 24.6 10.4 37.6 1.8 13 2.2 25.9 3.7 36.8 1.5 10.9 4.1 19.4 8.6 29.5 4.5 10.1 10.9 21.6 19.3 32 8.5 10.4 19 19.5 31 27.3 12 7.8 25.3 14.2 41.6 18 16.3 3.8 35.6 5.1 134.6 5.1 99 0 277.8-1.4 371.1-3.6 93.3-2.2 101-5.3 111.8-10.8 10.8-5.5 24.9-13.3 37.2-23.8 12.3-10.5 23.2-24 30.2-38.2 7-14.2 10.2-28.7 11.6-53.5 1.5-24.7 1.3-59.4-1.1-83-2.4-23.5-7-35.9-13.4-47.9-6.4-12-14.6-23.5-26.1-33.7-11.6-10.2-26.5-18.9-41.1-25.2-14.6-6.3-28.7-10.1-67.8-11.7-39.1-1.6-103.1-1-139.8 2.2-36.7 3.2-46.1 9-57.4 17.1-11.4 8.1-24.7 18.4-35.6 31.5-10.9 13-19.2 28.4-23.8 38.3-4.6 9.9-5.4 14.1-6.3 44.4-0.9 30.3-1.9 86.8-3 118.9-1.1 32.1-2.3 39.9-4 45.1-1.7 5.2-3.9 7.8-5.9 9.9-2 2.1-3.7 3.7-6.7 5.5-3 1.8-7.2 3.8-11.3 5.2-4 1.4-7.8 2.2-14 3.2-6.2 1-14.8 2.2-53.1 2.5-38.3 0.3-106.3-0.3-144.8-2-38.5-1.7-47.5-4.5-58.5-9.7-11-5.2-23.9-12.7-34.6-22-10.8-9.3-19.3-20.2-26-32.9-6.7-12.7-11.5-27-14.2-41.9-2.7-14.9-3.3-30.6-5.6-44.1-2.3-13.5-6.3-24.8-11.5-35.2-5.2-10.4-11.6-19.7-19.9-28.8-8.4-9.1-18.7-17.8-30.7-24.9-12-7.1-25.5-12.5-37.1-16.1-11.6-3.6-21.1-5.4-92.3-6.5-71.2-1.1-204.4-1.6-274.9 0-70.5 1.6-78.4 5.2-87.8 10.2-9.4 5-20.2 11.5-29.7 19-9.5 7.5-17.7 16.1-25 26.1-7.4 10-14 21.3-18.6 33.2-4.7 11.9-7.5 24.2-8.9 34.8-1.4 10.6-1.4 19.3-1.1 88.5 0.3 69.2 0.9 198.8 2.2 266.1 1.3 67.3 3.2 72.2 6.6 81.1 3.4 8.9 8.2 21.7 15.8 33.5 7.5 11.8 17.7 22.6 28 30.8 10.3 8.3 20.6 14.1 31.5 18.7 10.9 4.6 22.2 8 159.5 9.8 137.3 1.8 400.5 2 535.8 1.3 135.2-0.7 142.4-2.3 152.8-6.4 10.5-4.1 23.9-10.6 35.7-18.7 11.8-8 21.9-17.5 30.1-28.2 8.3-10.7 14.8-22.5 20.1-34.3 5.3-11.7 9.4-23.3 10.2-69.3 0.8-46-1.8-124.7-9.8-169.4-8-44.8-20.8-51.7-32.9-56.1-12.2-4.4-23.4-6.1-32.1-6.8-8.7-0.7-14.9-0.4-20.5-0.1-5.5 0.3-10.4 0.7-200.4 0.5-190-0.2-565.2-1.1-940.5-2" />

  <g id="map" x="0" y="0" transform="scale(1) translate(0,0)">
    <image href="https://i.imgur.com/WaWS3m2.png">
    </image>
  </g>  
     
       <rect x="298" y="800" width="71" height="8" fill="gold" /> 
         <rect x="296" y="814" width="75" height="8" fill="#F3F3F3" />  
           <rect x="294" y="827" width="77" height="9" fill="gold" /> 
            <rect x="292" y="840" width="83" height="9.5" fill="#F3F3F3" /> 
           <rect x="290" y="855" width="87" height="11" fill="gold" />              
           <!-- Знак пешеходного перехода -->
       <image href="https://i.stack.imgur.com/1ILIG.jpg" x="260" y="695" width="40px" height="40px" />  
 
  
     <!-- Анимация пешеходов -->
  <use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:blue; fill:black;"> 
     <animateMotion id="an1"
       begin="startGreen.begin"
       dur="10s"
       repeatCount="1"  >
          <mpath xlink:href="#child"/>
     </animateMotion>    
   </use>  
     <use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:green; fill:black;"> 
       <animateMotion id="an2"
          begin="startGreen.begin+4s"
          dur="10s"
          repeatCount="1"  >
          <mpath xlink:href="#child"/>
       </animateMotion> 
     </use>  
          <use xlink:href="#Man" transform="translate(0,0) scale(1.5)" style="stroke:black; fill:black;"> 
       <animateMotion id="an3"
          begin="startGreen.begin"
          dur="10s"
          repeatCount="1"  >
          <mpath xlink:href="#child2"/>
       </animateMotion> 
     </use>
   <use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:red; fill:black;"> 
     <animateMotion id="an4"
           begin="startGreen.begin"
           dur="15s"
           repeatCount="1"  >
              <mpath xlink:href="#home1"/>
     </animateMotion>    
   </use>     
       <use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:black; fill:black;"> 
          <animateMotion id="an5"
              begin="startGreen.begin-3s"
              dur="10s"
              repeatCount="1"  >
              <mpath xlink:href="#home2"/>
         </animateMotion>    
      </use>      
        <use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:blue; fill:black;"> 
          <animateMotion id="an6"
              begin="startGreen.begin-3s"
              dur="12s"
              repeatCount="1"  >
              <mpath xlink:href="#home2"/>
          </animateMotion>    
       </use>    

           <use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:red; fill:black;"> 
          <animateMotion id="an7"
              begin="startGreen.begin-5s"
              dur="14s"
              repeatCount="1"  >
              <mpath xlink:href="#home2"/>
          </animateMotion>    
       </use>      
      
<use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:brown; fill:black;"> 
          <animateMotion id="an8"
              begin="startGreen.begin"
              dur="6s"
              repeatCount="1"  >
              <mpath xlink:href="#back"/>
         </animateMotion>    
</use>      
    <use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:blue; fill:black;"> 
          <animateMotion id="an9"
              begin="startGreen.begin-2s"
              dur="8s"
              repeatCount="1"  >
              <mpath xlink:href="#back"/>
         </animateMotion>    
    </use>      
<use xlink:href="#Man" transform="translate(0,0) scale(2)" style="stroke:brown; fill:black;"> 
          <animateMotion id="an9"
              begin="startGreen.begin-4s"
              dur="8s"
              repeatCount="1"  >
              <mpath xlink:href="#back"/>
         </animateMotion>    
</use>      

  <g transform="translate(312 675) scale(0.3)">
         <!-- верхняя крышка светофора-->
<circle cx="270" cy="55"  r="30" style="fill:grey; " />
            <!-- корпус светофора -->
<rect x="240" y="40" width="60" height="190" style="fill:gray;" />
   
        <!-- секции светофора -->
<g style="fill:none; stroke:black; stroke-width:2px;">
 <rect x="240" y="40" width="60" height="60"  />
 <rect x="240" y="103" width="60" height="60"  />
 <rect x="240" y="166" width="60" height="60"  />
</g> 
    <!-- сигнальные лампочки-->
<circle cx="270" cy="70"  r="20" fill="red" opacity="0.4" >
  <animate id="startRed" attributeName="opacity" begin="0s;smallGreen.end" dur="0.1s" to="1" fill="freeze" /> 
    <animate id="stopRed" attributeName="opacity" begin="startRed.end+5s" dur="0.1s" to="0.4" fill="freeze" /> 
    <animate id="bigRed" attributeName="r" begin="startRed.begin" dur="0.1s" to="28" fill="freeze" /> 
     <animate id="smallRed" attributeName="r" begin="bigRed.end+5s" dur="0.1s" to="20" fill="freeze" />
</circle>

<circle cx="270" cy="133"  r="20" fill="yellow" opacity="0.4" > 
   <animate id="startYellow" attributeName="opacity" begin="smallRed.end" dur="0.1s" to="1" fill="freeze" /> 
     <animate id="stopYellow" attributeName="opacity" begin="smallRed.end+2s" dur="0.1s" to="0.4" fill="freeze" /> 
    
    <animate id="bigYellow" attributeName="r" begin="smallRed.end" dur="0.1s" to="28" fill="freeze" /> 
      <animate id="smallYellow" attributeName="r" begin="smallRed.end +2s" dur="0.1s" to="22" fill="freeze" />
</circle>   
<circle cx="270" cy="196"  r="20" fill="lime" opacity="0.4" >
    <animate id="startGreen" attributeName="opacity" begin="smallYellow.end" dur="0.1s" to="1" fill="freeze" /> 
      <animate id="stopGreen" attributeName="opacity" begin="smallYellow.end+10s" dur="0.1s" to="0.4" fill="freeze" /> 
        <animate id="bigGreen" attributeName="r" begin="smallYellow.end" dur="0.1s" to="28" fill="freeze" /> 
      <animate id="smallGreen" attributeName="r" begin="smallYellow.end +10s" dur="0.1s" to="22" fill="freeze" />
</circle>   
      
          <!-- стойка светофора -->
<rect x="260" y="226" width="20" height="174" style="fill:gray;" /> 
  </g>        
   <!--Автомобиль-->
  <g id="car" >
  <!--Зеркала-->
<path transform="scale(0.1)" d="M371 88l-31-77c-3-6-9-11-17-11h-23l35 88zm0 142h-36l-35 88h23c8 0 14-5 17-11z" fill="red" />
  <!--Кузов-->
    <path transform="scale(0.1)" d="M492 224l13-30c9-22 9-48 0-70l-13-30a88 88 0 0 0-88-53L256 53 104 40c-36-3-70 17-86 49l-3 7c-20 40-20 86 0 126l3 7a88 88 0 0 0 86 49l152-13 148 12c38 3 73-18 88-53z" fill="orangered" />
    <!--Тень кузова-->
    <path  transform="scale(0.1)" d="M396 277c66-50 95-134 74-214 9 9 17 19 22 31l13 30c9 22 9 48 0 70l-13 30a88 88 0 0 1-88 53z" fill="red" />
    <!--Переднее стекло-->
    <path transform="scale(0.1)" d="M369 91l-2-3c-3-5-10-8-16-7l-77 7v142l77 7c6 1 13-2 16-7l2-3c27-41 27-95 0-136z" fill="white" />
    <!--Тень переднего стекла-->
    <path transform="scale(0.1)" d="M370 92c26 41 26 94-1 135l-2 3c-3 5-10 8-16 7l-59-6c44-33 72-84 78-139z" fill="lightgray" />
    <!--Заднее стекло-->
    <path transform="scale(0.1)" d="M150 88v142l-41 6c-7 2-14-2-18-8l-9-18c-18-32-18-70 0-102l9-18c4-6 11-10 18-8z" fill="white" />
    <!--Тень заднего стекла-->
    <path transform="scale(0.1)" d="M91 228l-5-9c31-35 53-76 64-121v132l-41 6c-7 2-14-2-18-8z" fill="lightgray" />
    <!--Фары-->
    <path transform="scale(0.1)" d="M411 72l53 36-10 15-53-36zm43 124l10 15-54 35-10-15z" fill="yellow" />
     </g> 
    <path id="car1" d="M-15,-10 L15,0 L -15,10 z" fill="yellow" stroke="red" stroke-width="7.06"/>
</svg>
</div>

Как реализовать остановку скроллинга (передвижения) машины на красный свет (зеленый со стороны пешеходов ) при приближении к зоне зебры?

Update

Цитата из комментария:

Вы абсолютно правильно поняли суть проблемы. У svg одноуровневое управление анимациями. Нет одновременного срабатывания событий в условии запуска, остановки одной анимации в атрибуте begin. Нет возможности назначить логическое условие И, то есть:

  1. место нахождения автомобиля (у зебры)
    И
  2. зеленый свет светофора для пешеходов.

Для решения нужен JS или canvas.

введите сюда описание изображения

5
  • 1
    Может светофор менять состояние зебры, чтобы машина останавливалась только перед "закрытой" зеброй? Если у зебры не бывает состояний, то добавлять светофором "закрывающую зебру", перед которой останавливался бы автомобиль? То есть, вместо соблюдения двух условий создать каскад, когда второе условие обусловлено первым. 2 ноя 2021 в 20:42
  • Тогда ещё одно условие надо в котором - если пешеход на тратуаре что бы авто стояло вне зависимости от светофора.. 3 ноя 2021 в 0:44
  • 1
    @Gleb Kemarsky Вы абсолютно правильно поняли суть проблемы. У svg одноуровневое управление анимациями. Нет одновременного срабатывания событий в условии запуска, остановки одной анимации в атрибуте begin Нет возможности назначить логическое условие И, то есть 1. место нахождения автомобиля (у зебры) И 2. зеленый свет светофора для пешеходов. Для решения нужен JS или canvas. 3 ноя 2021 в 8:48
  • 1
    @Gleb Kemarsky Ваша идея, - закрывать зебру, после срабатывания запрещаюшего сигнала, к сожалению, не сработает. Так как движение автомобиля управляется скроллингом и он будет останавливаться в любом месте трассы (запрет скроллинга JS) на зеленый свет светофора для пешеходов, а следовательно на активацию зебры. 3 ноя 2021 в 8:50
  • @Айболит согласен, хорошо бы выполнять правила ПДД, но начнем с самого важного,- обучим программу, не наезжать на пешехода, находящегося на зебре при запрещающих сигналах светофора. 3 ноя 2021 в 8:59

2 ответа 2

1

Для управления движения машинкой добавим флаг moving, который установим в true пока нажата кнопка 🠕

для установки используем обработчик keydown

document.addEventListener('keydown', (e) => {
    if (e.key == 'ArrowUp') {
        moving = true;
    }
});

Для сбрасывания - обработчик keyup

document.addEventListener('keyup', (e) => {
    if (e.key == 'ArrowUp') {
        moving = false;
    }
})

Теперь в обработчике requestAnimationFrames двигаем машину только если флаг выставлен:

if (moving) {
    car.move(cross.rect, trafficLight, mans);
}

var ctx = canvas.getContext("2d");
var main = async() => {
  var {
    back,
    mans,
    trafficLight,
    cross,
    car
  } = await init();

  var moving = false;

  var drawable = back
    .concat(cross)
    .concat(mans)
    .concat(trafficLight)
    .concat(car);
  mans.forEach((m) => setTimeout(() => m.start(), Math.random() * 1000));
  requestAnimationFrame(function draw(timestamp) {
    drawable.forEach((d) => d.draw(ctx));

    mans.forEach((m) => m.move(cross.rect, trafficLight));
    if (moving) {
      car.move(cross.rect, trafficLight, mans);
    }
    requestAnimationFrame(draw);
  });

  document.addEventListener('keydown', (e) => {
    if (e.key == 'ArrowUp') {
      moving = true;
    }
  });

  document.addEventListener('keyup', (e) => {
    if (e.key == 'ArrowUp') {
      moving = false;
    }
  })


  function loadImage(src) {
    return new Promise((r, e) => {
      var img = new Image();
      img.onload = () => r(img);
      img.onerror = e;
      img.src = src;
    });
  }

  async function init() {
    var [background, road, sign] = await Promise.all([
      loadImage("https://i.imgur.com/WaWS3m2.png"),
      loadImage("https://i.imgur.com/uTmJYO7.png"),
      loadImage("https://i.stack.imgur.com/1ILIG.jpg")
    ]);

    var tl = new TrafficLights(393, 690, [{
        state: 0b001,
        timeout: 3000,
        canWalk: false
      },
      {
        state: 0b011,
        timeout: 1500,
        canWalk: false
      },
      {
        state: 0b100,
        timeout: 3000,
        canWalk: true
      },
      {
        state: 0b0,
        timeout: 300,
        canWalk: true
      },
      {
        state: 0b100,
        timeout: 1000,
        canWalk: true
      },
      {
        state: 0b0,
        timeout: 300,
        canWalk: true
      },
      {
        state: 0b100,
        timeout: 1000,
        canWalk: true
      },
      {
        state: 0b0,
        timeout: 300,
        canWalk: true
      },
      {
        state: 0b100,
        timeout: 1000,
        canWalk: true
      },
      {
        state: 0b010,
        timeout: 1500,
        canWalk: false
      }
    ]);
    tl.start();
    return {
      back: [new Background(background, road), new CrossSign(sign, 260, 695)],
      cross: new Cross(299, 797),
      mans: [
        new Man("red", `m328 893 1-212M344 864`),
        new Man(
          "blue",
          `m344.35582,883.69183 c 0,0 -34.63139,-111.56426 0,-145.53606 29.52729,-28.96492 84.99455,-11.19516 124.06352,2.38584 15.72518,5.46632 24.12207,24.52029 39.76395,30.2206 78.91988,28.76045 173.36704,37.53827 258.46569,18.29141`
        ),
        new Man("green", `m329 682c0 0-23 32-25 41-13 54 14 143 14 143`)
      ],
      trafficLight: tl,
      car: new Car(
        "M-99.9 458.3C405 455.9 909.9 453.5 1168.1 451.5c258.3-2 269.8-3.7 284-9 14.2-5.3 31-14.2 44.5-25.7 13.5-11.5 24-25.7 30.9-40 6.9-14.3 10.3-28.6 12-52.9 1.7-24.3 1.7-59-0.7-82.6-2.4-23.5-7.2-36.5-14.1-48.6-6.8-12.1-15.9-23.8-27.6-34.1-11.7-10.3-26-19.2-41-25.4-15.1-6.2-30.4-9.6-69.2-10.9-38.8-1.4-100.8-0.8-138.2 3.2-37.4 4-50.2 11.4-61.6 19.2-11.5 7.9-21.6 16.3-31 28.1-9.4 11.9-17.9 27.2-23.1 42.3-5.2 15.1-7 29.8-6.3 113.4 0.7 83.6 3.9 235.9 2.4 318.2-1.5 82.3-7.7 94.4-13.2 104.4-5.5 9.9-10.6 17.8-19.2 27.4-8.6 9.6-20.7 20.9-34.1 29.3-13.4 8.4-27.9 13.8-167.6 16.5-139.7 2.7-404.5 2.7-542.3 1.2-137.8-1.5-149-4.5-161.3-10.4-12.4-5.9-26.1-14.7-37.6-26.8-11.5-12.2-20.6-27.7-26.5-41.9-5.9-14.1-8.5-26.9-9.7-101.5-1.2-74.6-1-211 0.4-283.5 1.4-72.5 4-81.1 8.9-91.2 4.9-10.2 12.1-21.9 21.1-32.7 9.1-10.8 20-20.5 31.3-27.6 11.3-7.1 22.8-11.5 34.8-14.2 12-2.8 24.7-4 94.9-4.5 70.2-0.5 198-0.3 264.3 0.6 66.3 0.9 70.7 2.5 77.6 5 6.9 2.5 16.1 5.9 25.9 12 9.9 6.1 20.4 14.9 29.5 25 9.1 10.2 16.7 21.7 22 33.8 5.4 12.1 8.6 24.6 10.4 37.6 1.8 13 2.2 25.9 3.7 36.8 1.5 10.9 4.1 19.4 8.6 29.5 4.5 10.1 10.9 21.6 19.3 32 8.5 10.4 19 19.5 31 27.3 12 7.8 25.3 14.2 41.6 18 16.3 3.8 35.6 5.1 134.6 5.1 99 0 277.8-1.4 371.1-3.6 93.3-2.2 101-5.3 111.8-10.8 10.8-5.5 24.9-13.3 37.2-23.8 12.3-10.5 23.2-24 30.2-38.2 7-14.2 10.2-28.7 11.6-53.5 1.5-24.7 1.3-59.4-1.1-83-2.4-23.5-7-35.9-13.4-47.9-6.4-12-14.6-23.5-26.1-33.7-11.6-10.2-26.5-18.9-41.1-25.2-14.6-6.3-28.7-10.1-67.8-11.7-39.1-1.6-103.1-1-139.8 2.2-36.7 3.2-46.1 9-57.4 17.1-11.4 8.1-24.7 18.4-35.6 31.5-10.9 13-19.2 28.4-23.8 38.3-4.6 9.9-5.4 14.1-6.3 44.4-0.9 30.3-1.9 86.8-3 118.9-1.1 32.1-2.3 39.9-4 45.1-1.7 5.2-3.9 7.8-5.9 9.9-2 2.1-3.7 3.7-6.7 5.5-3 1.8-7.2 3.8-11.3 5.2-4 1.4-7.8 2.2-14 3.2-6.2 1-14.8 2.2-53.1 2.5-38.3 0.3-106.3-0.3-144.8-2-38.5-1.7-47.5-4.5-58.5-9.7-11-5.2-23.9-12.7-34.6-22-10.8-9.3-19.3-20.2-26-32.9-6.7-12.7-11.5-27-14.2-41.9-2.7-14.9-3.3-30.6-5.6-44.1-2.3-13.5-6.3-24.8-11.5-35.2-5.2-10.4-11.6-19.7-19.9-28.8-8.4-9.1-18.7-17.8-30.7-24.9-12-7.1-25.5-12.5-37.1-16.1-11.6-3.6-21.1-5.4-92.3-6.5-71.2-1.1-204.4-1.6-274.9 0-70.5 1.6-78.4 5.2-87.8 10.2-9.4 5-20.2 11.5-29.7 19-9.5 7.5-17.7 16.1-25 26.1-7.4 10-14 21.3-18.6 33.2-4.7 11.9-7.5 24.2-8.9 34.8-1.4 10.6-1.4 19.3-1.1 88.5 0.3 69.2 0.9 198.8 2.2 266.1 1.3 67.3 3.2 72.2 6.6 81.1 3.4 8.9 8.2 21.7 15.8 33.5 7.5 11.8 17.7 22.6 28 30.8 10.3 8.3 20.6 14.1 31.5 18.7 10.9 4.6 22.2 8 159.5 9.8 137.3 1.8 400.5 2 535.8 1.3 135.2-0.7 142.4-2.3 152.8-6.4 10.5-4.1 23.9-10.6 35.7-18.7 11.8-8 21.9-17.5 30.1-28.2 8.3-10.7 14.8-22.5 20.1-34.3 5.3-11.7 9.4-23.3 10.2-69.3 0.8-46-1.8-124.7-9.8-169.4-8-44.8-20.8-51.7-32.9-56.1-12.2-4.4-23.4-6.1-32.1-6.8-8.7-0.7-14.9-0.4-20.5-0.1-5.5 0.3-10.4 0.7-200.4 0.5-190-0.2-565.2-1.1-940.5-2"
      )
    };
  }
}
main();

class Background {
  constructor(bgImg, roadImg) {
    this.bgImg = bgImg;
    this.roadImg = roadImg;
  }

  draw(ctx) {
    ctx.drawImage(this.bgImg, 0, 0);
    ctx.drawImage(this.roadImg, 0, 0);
  }
}

class Cross {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.w = 71;
    this.h = 10;
    this.gap = 5;
    this.lineCount = 5;
    this.rect = {
      x: this.x,
      y: this.y - this.h,
      width: this.w,
      height: (this.h + this.gap) * this.lineCount + this.h
    };
  }

  drawLine(ctx, x, y, w, h, color) {
    ctx.save();
    ctx.fillStyle = color;
    ctx.fillRect(x, y, w, h);
    ctx.restore();
  }
  draw(ctx) {
    for (var i = 0; i < this.lineCount; i++) {
      this.drawLine(
        ctx,
        this.x,
        this.y + i * (this.h + this.gap),
        this.w,
        this.h,
        i % 2 ? "white" : "gold"
      );
    }
  }
}
class CrossSign {
  constructor(signImg, x, y) {
    this.signImg = signImg;
    this.x = x;
    this.y = y;
  }

  draw(ctx) {
    ctx.drawImage(this.signImg, this.x, this.y, 40, 40);
  }
}
class Man {
  constructor(color, path) {
    this.color = color;
    this.lines = [
      `M-3,0 0,10 3,0 M0,10 0,16 l 4,-5 M0,16 l-4,-5 M0,16 c4,4 -4,4 0,0`,
      `M 0,0 0,10 0,0 M0,10 0,16 l 0,-5 M0,16 l 0,-5 M0,16 c4,4 -4,4 0,0`
    ].map((p) => new Path2D(p));
    this.currentStep = 0;
    this.currentMove = 0;
    this.path = createMovePath(path);
    this.total = this.path.getTotalLength();
    var point = this.path.getPointAtLength(this.currentMove);
    this.x = point.x;
    this.y = point.y;
    this.visible = false;
  }

  draw(ctx) {
    if (!this.visible) return;

    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.scale(2, -2);
    ctx.strokeStyle = this.color;
    ctx.lineWidth = 2;
    ctx.stroke(this.lines[this.currentStep]);
    ctx.restore();
  }

  update() {
    this.currentStep = (this.currentStep + 1) % this.lines.length;
  }
  start() {
    this.interval = setInterval(() => {
      this.update();
    }, 300);
    this.visible = true;
    this.currentMove = -1;
    this.move();
  }
  stop() {
    clearInterval(this.interval);
    this.visible = false;
  }
  canMove(point, crossRect, tl) {
    if (!crossRect && !tl) return true;

    if (isInRect(this, crossRect, 10)) return true;

    if (isInRect(point, crossRect, 10)) return tl.canWalk();

    return true;
  }
  move(crossRect, tl) {
    if (!this.visible) return;
    if (this.currentMove >= this.total) {
      this.stop();
      setTimeout(() => this.start(), Math.random() * 1000 + 1000);
      return;
    }
    var point = this.path.getPointAtLength(this.currentMove + 1);
    if (this.canMove(point, crossRect, tl)) {
      this.currentMove += 1;
      this.x = point.x;
      this.y = point.y;
    }
  }
}
class Light {
  constructor(x, y, size, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.size = size;
    this.active = false;
  }

  draw(ctx) {
    ctx.save();
    ctx.globalAlpha = this.active ? 1 : 0.7;
    ctx.strokeStyle = "black";
    ctx.strokeWidth = 2;
    ctx.strokeRect(this.x, this.y, this.size, this.size);
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(
      this.x + this.size / 2,
      this.y + this.size / 2,
      this.active ? this.size / 2 - 2 : this.size / 4,
      0,
      Math.PI * 2
    );
    ctx.fill();
    ctx.restore();
  }

  toggle(state = undefined) {
    this.active = state === undefined ? !this.active : state;
  }
}

class TrafficLights {
  constructor(x, y, program) {
    this.x = x;
    this.y = y;
    this.boxSize = 18;
    this.lights = this.initLights(["red", "yellow", "lime"]);
    this.program = program;
    this.currentStep = -1;
  }

  initLights(colors) {
    var lights = new Array(colors.length);
    for (var i = 0; i < colors.length; i++) {
      lights[i] = new Light(0, this.boxSize * i, this.boxSize, colors[i]);
    }

    return lights;
  }

  update() {
    this.currentStep = (this.currentStep + 1) % this.program.length;
    this.lights.forEach((l, i) => {
      l.toggle(this.program[this.currentStep].state & (1 << i));
    });
  }
  start() {
    var self = this;
    self.update();
    this.interval = setTimeout(function timer() {
      self.update();
      self.interval = setTimeout(timer, self.program[self.currentStep].timeout);
    }, this.program[this.currentStep].timeout);
  }
  stop() {
    clearInterval(this.interval);
  }
  drawLine(ctx, size) {
    ctx.save();
    ctx.translate(this.x - size / 2, this.y);
    ctx.fillStyle = "gray";
    ctx.fillRect(0, 0, size, 105); // 120 h
    ctx.restore();
  }
  drawBox(ctx) {
    ctx.save();
    ctx.translate(this.x - this.boxSize / 2, this.y);
    this.drawCap(ctx);
    ctx.fillStyle = "gray";
    ctx.fillRect(0, 0, this.boxSize, this.boxSize * this.lights.length);
    this.lights.forEach((l) => l.draw(ctx));
    ctx.restore();
  }
  drawCap(ctx) {
    ctx.save();
    ctx.fillStyle = "gray";
    ctx.beginPath();
    ctx.moveTo(2, 0);
    ctx.arcTo(
      this.boxSize / 2, -this.boxSize,
      this.boxSize - 2,
      0,
      this.boxSize / 2 - 1.5
    );
    ctx.closePath();
    ctx.fill();
    ctx.restore();
  }
  draw(ctx) {
    this.drawLine(ctx, 8);
    this.drawBox(ctx);
  }
  canWalk() {
    return this.program[this.currentStep].canWalk;
  }
}

class FillPath {
  constructor(path, bgColor) {
    this.path = new Path2D(path);
    this.bgColor = bgColor;
  }

  draw(ctx) {
    ctx.save();
    ctx.fillStyle = this.bgColor;
    ctx.fill(this.path);
    ctx.restore();
  }
}

class Car {
  constructor(path) {
    this.currentMove = 0;
    this.path = createMovePath(path);
    this.total = this.path.getTotalLength();
    var point = this.path.getPointAtLength(this.currentMove);
    this.x = point.x;
    this.y = point.y;
    this.angle = 0;
    this.stepInFrame = 7;

    this.mirror = new FillPath(
      "M371 88l-31-77c-3-6-9-11-17-11h-23l35 88zm0 142h-36l-35 88h23c8 0 14-5 17-11z",
      "red"
    );
    this.back = new FillPath(
      "M492 224l13-30c9-22 9-48 0-70l-13-30a88 88 0 0 0-88-53L256 53 104 40c-36-3-70 17-86 49l-3 7c-20 40-20 86 0 126l3 7a88 88 0 0 0 86 49l152-13 148 12c38 3 73-18 88-53z",
      "orangered"
    );
    this.backShadow = new FillPath(
      "M396 277c66-50 95-134 74-214 9 9 17 19 22 31l13 30c9 22 9 48 0 70l-13 30a88 88 0 0 1-88 53z",
      "red"
    );
    this.forwardGlass = new FillPath(
      "M369 91l-2-3c-3-5-10-8-16-7l-77 7v142l77 7c6 1 13-2 16-7l2-3c27-41 27-95 0-136z",
      "white"
    );
    this.forwardGlassShadow = new FillPath(
      "M370 92c26 41 26 94-1 135l-2 3c-3 5-10 8-16 7l-59-6c44-33 72-84 78-139z",
      "lightgray"
    );
    this.backGlass = new FillPath(
      "M150 88v142l-41 6c-7 2-14-2-18-8l-9-18c-18-32-18-70 0-102l9-18c4-6 11-10 18-8z",
      "white"
    );
    this.backGlassShadow = new FillPath(
      "M91 228l-5-9c31-35 53-76 64-121v132l-41 6c-7 2-14-2-18-8z",
      "lightgray"
    );
    this.light = new FillPath(
      "M411 72l53 36-10 15-53-36zm43 124l10 15-54 35-10-15z",
      "yellow"
    );
  }

  draw(ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.scale(0.1, 0.1);
    ctx.rotate(this.angle);
    this.mirror.draw(ctx);
    this.back.draw(ctx);
    this.backShadow.draw(ctx);
    this.forwardGlass.draw(ctx);
    this.forwardGlassShadow.draw(ctx);
    this.backGlass.draw(ctx);
    this.backGlassShadow.draw(ctx);
    this.light.draw(ctx);
    ctx.restore();
  }

  canMove(point, crossRect, tl, mans) {
    if (!crossRect && !tl) return true;
    if (isInRect(this, crossRect, 50))
      return mans.every((m) => !isInRect(m, crossRect, 10));

    if (isInRect(point, crossRect, 50))
      return !tl.canWalk() && mans.every((m) => !isInRect(m, crossRect, 10));

    return true;
  }
  move(crossRect, tl, mans) {
    for (var i = 0; i < this.stepInFrame; i++) {
      var point = this.path.getPointAtLength(this.currentMove + 1);

      if (!this.canMove(point, crossRect, tl, mans)) {
        return;
      }
      this.currentMove = (this.currentMove + 1) % this.total;
      this.x = point.x;
      this.y = point.y;

      if (this.currentMove + 1 <= this.total) {
        var posAhead = this.path.getPointAtLength(this.currentMove + 1);
        this.angle = Math.atan2(posAhead.y - point.y, posAhead.x - point.x);
      } else {
        var posBehind = this.path.getPointAtLength(this.currentMove - 1);
        this.angle = Math.atan2(point.y - posBehind.y, point.x - posBehind.x);
      }
    }
  }
}


function createMovePath(path) {
  let p = document.createElementNS("http://www.w3.org/2000/svg", "path");
  p.setAttribute("d", path);
  return p;
}

function isInRect(point, rect, gap) {
  return point.y >= rect.y - gap && point.y <= rect.y + rect.height + gap &&
    point.x >= rect.x - gap && point.x <= rect.x + rect.width + gap;
}
html,
body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
}

canvas {
  max-width: 100%;
  max-height: 100%;
}
<canvas id="canvas" width="1600" height="900"></canvas>

7
  • ♦ Просто здорово! Впечатляет! Проверил, - пешеходов невозможно задавить на зебре при горящем зелёном свете светофора для пешеходов. 7 апр 2022 в 18:22
  • @Alexandr_TT, по идее невозможно должно быть и в случае если зеленый уже прошел но пешеход еще на зебре - но тут надо еще такой момент подловить, чтобы проверить
    – Grundy
    7 апр 2022 в 18:23
  • После светофора тоже останавливается :D
    – Qwertiy
    7 апр 2022 в 18:24
  • @Alexandr_TT ну и на самом деле надо получше проверить методы canMove который определяют можно ли сделать следующий шаг человеку или машине :)
    – Grundy
    7 апр 2022 в 18:24
  • @Qwertiy, ага :) тоже несколько раз попадал - проблема в проверке площади, возможно либо на проверяемом квадрате застукивает, либо из-за разворота проверяем не совсем тот прямоугольник :) ну и с gap можно поиграть еще. Я сейчас по сути только точку из пути проверяю, по хорошему надо проверять еще прямоугольник самой машины :)
    – Grundy
    7 апр 2022 в 18:25
1

Перенос на canvas можно разделить на несколько частей:

  1. отрисовка статического фона, дороги и знака
  2. реализация светофора
  3. реализация людей
  4. реализация машины

Движение по path, осуществляется по тому же принципу, что и в вопросе:

  1. берем текущий шаг
  2. получаем координаты в path
  3. обновляем координаты передвигаемого объекта

Далее перед совершением каждого шага, необходимо проверить можно ли его совершить.

Для этого должно соблюдаться несколько условий:

  1. если объект уже на переходе - он продолжает движение и завершает переход/переезд

  2. если следующий шаг приходится на переход - проверяется состояние светофора.

  3. для машины дополнительно проверяется наличие людей на переходе

Проверить выход на переход можно с помощью простой функции

function isInRect(point, rect, gap) {
  return point.y >= rect.y - gap && point.y <= rect.y + rect.height + gap &&
    point.x >= rect.x - gap && point.x <= rect.x + rect.width + gap;
}

Которая проверяет вхождение точки point, в некоторый прямоугольник rect, c заданным допуском gap.

Пример возможной реализации:

var ctx = canvas.getContext("2d");
var main = async() => {
  var {
    back,
    mans,
    trafficLight,
    cross,
    car
  } = await init();

  var drawable = back
    .concat(cross)
    .concat(mans)
    .concat(trafficLight)
    .concat(car);
  mans.forEach((m) => setTimeout(() => m.start(), Math.random() * 1000));
  requestAnimationFrame(function draw(timestamp) {
    drawable.forEach((d) => d.draw(ctx));

    mans.forEach((m) => m.move(cross.rect, trafficLight));
    car.move(cross.rect, trafficLight, mans);
    requestAnimationFrame(draw);
  });

  function loadImage(src) {
    return new Promise((r, e) => {
      var img = new Image();
      img.onload = () => r(img);
      img.onerror = e;
      img.src = src;
    });
  }

  async function init() {
    var [background, road, sign] = await Promise.all([
      loadImage("https://i.imgur.com/WaWS3m2.png"),
      loadImage("https://i.imgur.com/uTmJYO7.png"),
      loadImage("https://i.stack.imgur.com/1ILIG.jpg")
    ]);

    var tl = new TrafficLights(393, 690, [{
        state: 0b001,
        timeout: 3000,
        canWalk: false
      },
      {
        state: 0b011,
        timeout: 1500,
        canWalk: false
      },
      {
        state: 0b100,
        timeout: 3000,
        canWalk: true
      },
      {
        state: 0b0,
        timeout: 300,
        canWalk: true
      },
      {
        state: 0b100,
        timeout: 1000,
        canWalk: true
      },
      {
        state: 0b0,
        timeout: 300,
        canWalk: true
      },
      {
        state: 0b100,
        timeout: 1000,
        canWalk: true
      },
      {
        state: 0b0,
        timeout: 300,
        canWalk: true
      },
      {
        state: 0b100,
        timeout: 1000,
        canWalk: true
      },
      {
        state: 0b010,
        timeout: 1500,
        canWalk: false
      }
    ]);
    tl.start();
    return {
      back: [new Background(background, road), new CrossSign(sign, 260, 695)],
      cross: new Cross(299, 797),
      mans: [
        new Man("red", `m328 893 1-212M344 864`),
        new Man(
          "blue",
          `m344.35582,883.69183 c 0,0 -34.63139,-111.56426 0,-145.53606 29.52729,-28.96492 84.99455,-11.19516 124.06352,2.38584 15.72518,5.46632 24.12207,24.52029 39.76395,30.2206 78.91988,28.76045 173.36704,37.53827 258.46569,18.29141`
        ),
        new Man("green", `m329 682c0 0-23 32-25 41-13 54 14 143 14 143`)
      ],
      trafficLight: tl,
      car: new Car(
        "M-99.9 458.3C405 455.9 909.9 453.5 1168.1 451.5c258.3-2 269.8-3.7 284-9 14.2-5.3 31-14.2 44.5-25.7 13.5-11.5 24-25.7 30.9-40 6.9-14.3 10.3-28.6 12-52.9 1.7-24.3 1.7-59-0.7-82.6-2.4-23.5-7.2-36.5-14.1-48.6-6.8-12.1-15.9-23.8-27.6-34.1-11.7-10.3-26-19.2-41-25.4-15.1-6.2-30.4-9.6-69.2-10.9-38.8-1.4-100.8-0.8-138.2 3.2-37.4 4-50.2 11.4-61.6 19.2-11.5 7.9-21.6 16.3-31 28.1-9.4 11.9-17.9 27.2-23.1 42.3-5.2 15.1-7 29.8-6.3 113.4 0.7 83.6 3.9 235.9 2.4 318.2-1.5 82.3-7.7 94.4-13.2 104.4-5.5 9.9-10.6 17.8-19.2 27.4-8.6 9.6-20.7 20.9-34.1 29.3-13.4 8.4-27.9 13.8-167.6 16.5-139.7 2.7-404.5 2.7-542.3 1.2-137.8-1.5-149-4.5-161.3-10.4-12.4-5.9-26.1-14.7-37.6-26.8-11.5-12.2-20.6-27.7-26.5-41.9-5.9-14.1-8.5-26.9-9.7-101.5-1.2-74.6-1-211 0.4-283.5 1.4-72.5 4-81.1 8.9-91.2 4.9-10.2 12.1-21.9 21.1-32.7 9.1-10.8 20-20.5 31.3-27.6 11.3-7.1 22.8-11.5 34.8-14.2 12-2.8 24.7-4 94.9-4.5 70.2-0.5 198-0.3 264.3 0.6 66.3 0.9 70.7 2.5 77.6 5 6.9 2.5 16.1 5.9 25.9 12 9.9 6.1 20.4 14.9 29.5 25 9.1 10.2 16.7 21.7 22 33.8 5.4 12.1 8.6 24.6 10.4 37.6 1.8 13 2.2 25.9 3.7 36.8 1.5 10.9 4.1 19.4 8.6 29.5 4.5 10.1 10.9 21.6 19.3 32 8.5 10.4 19 19.5 31 27.3 12 7.8 25.3 14.2 41.6 18 16.3 3.8 35.6 5.1 134.6 5.1 99 0 277.8-1.4 371.1-3.6 93.3-2.2 101-5.3 111.8-10.8 10.8-5.5 24.9-13.3 37.2-23.8 12.3-10.5 23.2-24 30.2-38.2 7-14.2 10.2-28.7 11.6-53.5 1.5-24.7 1.3-59.4-1.1-83-2.4-23.5-7-35.9-13.4-47.9-6.4-12-14.6-23.5-26.1-33.7-11.6-10.2-26.5-18.9-41.1-25.2-14.6-6.3-28.7-10.1-67.8-11.7-39.1-1.6-103.1-1-139.8 2.2-36.7 3.2-46.1 9-57.4 17.1-11.4 8.1-24.7 18.4-35.6 31.5-10.9 13-19.2 28.4-23.8 38.3-4.6 9.9-5.4 14.1-6.3 44.4-0.9 30.3-1.9 86.8-3 118.9-1.1 32.1-2.3 39.9-4 45.1-1.7 5.2-3.9 7.8-5.9 9.9-2 2.1-3.7 3.7-6.7 5.5-3 1.8-7.2 3.8-11.3 5.2-4 1.4-7.8 2.2-14 3.2-6.2 1-14.8 2.2-53.1 2.5-38.3 0.3-106.3-0.3-144.8-2-38.5-1.7-47.5-4.5-58.5-9.7-11-5.2-23.9-12.7-34.6-22-10.8-9.3-19.3-20.2-26-32.9-6.7-12.7-11.5-27-14.2-41.9-2.7-14.9-3.3-30.6-5.6-44.1-2.3-13.5-6.3-24.8-11.5-35.2-5.2-10.4-11.6-19.7-19.9-28.8-8.4-9.1-18.7-17.8-30.7-24.9-12-7.1-25.5-12.5-37.1-16.1-11.6-3.6-21.1-5.4-92.3-6.5-71.2-1.1-204.4-1.6-274.9 0-70.5 1.6-78.4 5.2-87.8 10.2-9.4 5-20.2 11.5-29.7 19-9.5 7.5-17.7 16.1-25 26.1-7.4 10-14 21.3-18.6 33.2-4.7 11.9-7.5 24.2-8.9 34.8-1.4 10.6-1.4 19.3-1.1 88.5 0.3 69.2 0.9 198.8 2.2 266.1 1.3 67.3 3.2 72.2 6.6 81.1 3.4 8.9 8.2 21.7 15.8 33.5 7.5 11.8 17.7 22.6 28 30.8 10.3 8.3 20.6 14.1 31.5 18.7 10.9 4.6 22.2 8 159.5 9.8 137.3 1.8 400.5 2 535.8 1.3 135.2-0.7 142.4-2.3 152.8-6.4 10.5-4.1 23.9-10.6 35.7-18.7 11.8-8 21.9-17.5 30.1-28.2 8.3-10.7 14.8-22.5 20.1-34.3 5.3-11.7 9.4-23.3 10.2-69.3 0.8-46-1.8-124.7-9.8-169.4-8-44.8-20.8-51.7-32.9-56.1-12.2-4.4-23.4-6.1-32.1-6.8-8.7-0.7-14.9-0.4-20.5-0.1-5.5 0.3-10.4 0.7-200.4 0.5-190-0.2-565.2-1.1-940.5-2"
      )
    };
  }
}
main();

class Background {
  constructor(bgImg, roadImg) {
    this.bgImg = bgImg;
    this.roadImg = roadImg;
  }

  draw(ctx) {
    ctx.drawImage(this.bgImg, 0, 0);
    ctx.drawImage(this.roadImg, 0, 0);
  }
}

class Cross {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.w = 71;
    this.h = 10;
    this.gap = 5;
    this.lineCount = 5;
    this.rect = {
      x: this.x,
      y: this.y - this.h,
      width: this.w,
      height: (this.h + this.gap) * this.lineCount + this.h
    };
  }

  drawLine(ctx, x, y, w, h, color) {
    ctx.save();
    ctx.fillStyle = color;
    ctx.fillRect(x, y, w, h);
    ctx.restore();
  }
  draw(ctx) {
    for (var i = 0; i < this.lineCount; i++) {
      this.drawLine(
        ctx,
        this.x,
        this.y + i * (this.h + this.gap),
        this.w,
        this.h,
        i % 2 ? "white" : "gold"
      );
    }
  }
}
class CrossSign {
  constructor(signImg, x, y) {
    this.signImg = signImg;
    this.x = x;
    this.y = y;
  }

  draw(ctx) {
    ctx.drawImage(this.signImg, this.x, this.y, 40, 40);
  }
}
class Man {
  constructor(color, path) {
    this.color = color;
    this.lines = [
      `M-3,0 0,10 3,0 M0,10 0,16 l 4,-5 M0,16 l-4,-5 M0,16 c4,4 -4,4 0,0`,
      `M 0,0 0,10 0,0 M0,10 0,16 l 0,-5 M0,16 l 0,-5 M0,16 c4,4 -4,4 0,0`
    ].map((p) => new Path2D(p));
    this.currentStep = 0;
    this.currentMove = 0;
    this.path = createMovePath(path);
    this.total = this.path.getTotalLength();
    var point = this.path.getPointAtLength(this.currentMove);
    this.x = point.x;
    this.y = point.y;
    this.visible = false;
  }

  draw(ctx) {
    if (!this.visible) return;

    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.scale(2, -2);
    ctx.strokeStyle = this.color;
    ctx.lineWidth = 2;
    ctx.stroke(this.lines[this.currentStep]);
    ctx.restore();
  }

  update() {
    this.currentStep = (this.currentStep + 1) % this.lines.length;
  }
  start() {
    this.interval = setInterval(() => {
      this.update();
    }, 300);
    this.visible = true;
    this.currentMove = -1;
    this.move();
  }
  stop() {
    clearInterval(this.interval);
    this.visible = false;
  }
  canMove(point, crossRect, tl) {
    if (!crossRect && !tl) return true;

    if (isInRect(this, crossRect, 10)) return true;

    if (isInRect(point, crossRect, 10)) return tl.canWalk();

    return true;
  }
  move(crossRect, tl) {
    if (!this.visible) return;
    if (this.currentMove >= this.total) {
      this.stop();
      setTimeout(() => this.start(), Math.random() * 1000 + 1000);
      return;
    }
    var point = this.path.getPointAtLength(this.currentMove + 1);
    if (this.canMove(point, crossRect, tl)) {
      this.currentMove += 1;
      this.x = point.x;
      this.y = point.y;
    }
  }
}
class Light {
  constructor(x, y, size, color) {
    this.x = x;
    this.y = y;
    this.color = color;
    this.size = size;
    this.active = false;
  }

  draw(ctx) {
    ctx.save();
    ctx.globalAlpha = this.active ? 1 : 0.7;
    ctx.strokeStyle = "black";
    ctx.strokeWidth = 2;
    ctx.strokeRect(this.x, this.y, this.size, this.size);
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.arc(
      this.x + this.size / 2,
      this.y + this.size / 2,
      this.active ? this.size / 2 - 2 : this.size / 4,
      0,
      Math.PI * 2
    );
    ctx.fill();
    ctx.restore();
  }

  toggle(state = undefined) {
    this.active = state === undefined ? !this.active : state;
  }
}

class TrafficLights {
  constructor(x, y, program) {
    this.x = x;
    this.y = y;
    this.boxSize = 18;
    this.lights = this.initLights(["red", "yellow", "lime"]);
    this.program = program;
    this.currentStep = -1;
  }

  initLights(colors) {
    var lights = new Array(colors.length);
    for (var i = 0; i < colors.length; i++) {
      lights[i] = new Light(0, this.boxSize * i, this.boxSize, colors[i]);
    }

    return lights;
  }

  update() {
    this.currentStep = (this.currentStep + 1) % this.program.length;
    this.lights.forEach((l, i) => {
      l.toggle(this.program[this.currentStep].state & (1 << i));
    });
  }
  start() {
    var self = this;
    self.update();
    this.interval = setTimeout(function timer() {
      self.update();
      self.interval = setTimeout(timer, self.program[self.currentStep].timeout);
    }, this.program[this.currentStep].timeout);
  }
  stop() {
    clearInterval(this.interval);
  }
  drawLine(ctx, size) {
    ctx.save();
    ctx.translate(this.x - size / 2, this.y);
    ctx.fillStyle = "gray";
    ctx.fillRect(0, 0, size, 105); // 120 h
    ctx.restore();
  }
  drawBox(ctx) {
    ctx.save();
    ctx.translate(this.x - this.boxSize / 2, this.y);
    this.drawCap(ctx);
    ctx.fillStyle = "gray";
    ctx.fillRect(0, 0, this.boxSize, this.boxSize * this.lights.length);
    this.lights.forEach((l) => l.draw(ctx));
    ctx.restore();
  }
  drawCap(ctx) {
    ctx.save();
    ctx.fillStyle = "gray";
    ctx.beginPath();
    ctx.moveTo(2, 0);
    ctx.arcTo(
      this.boxSize / 2, -this.boxSize,
      this.boxSize - 2,
      0,
      this.boxSize / 2 - 1.5
    );
    ctx.closePath();
    ctx.fill();
    ctx.restore();
  }
  draw(ctx) {
    this.drawLine(ctx, 8);
    this.drawBox(ctx);
  }
  canWalk() {
    return this.program[this.currentStep].canWalk;
  }
}

class FillPath {
  constructor(path, bgColor) {
    this.path = new Path2D(path);
    this.bgColor = bgColor;
  }

  draw(ctx) {
    ctx.save();
    ctx.fillStyle = this.bgColor;
    ctx.fill(this.path);
    ctx.restore();
  }
}

class Car {
  constructor(path) {
    this.currentMove = 0;
    this.path = createMovePath(path);
    this.total = this.path.getTotalLength();
    var point = this.path.getPointAtLength(this.currentMove);
    this.x = point.x;
    this.y = point.y;
    this.angle = 0;
    this.stepInFrame = 7;

    this.mirror = new FillPath(
      "M371 88l-31-77c-3-6-9-11-17-11h-23l35 88zm0 142h-36l-35 88h23c8 0 14-5 17-11z",
      "red"
    );
    this.back = new FillPath(
      "M492 224l13-30c9-22 9-48 0-70l-13-30a88 88 0 0 0-88-53L256 53 104 40c-36-3-70 17-86 49l-3 7c-20 40-20 86 0 126l3 7a88 88 0 0 0 86 49l152-13 148 12c38 3 73-18 88-53z",
      "orangered"
    );
    this.backShadow = new FillPath(
      "M396 277c66-50 95-134 74-214 9 9 17 19 22 31l13 30c9 22 9 48 0 70l-13 30a88 88 0 0 1-88 53z",
      "red"
    );
    this.forwardGlass = new FillPath(
      "M369 91l-2-3c-3-5-10-8-16-7l-77 7v142l77 7c6 1 13-2 16-7l2-3c27-41 27-95 0-136z",
      "white"
    );
    this.forwardGlassShadow = new FillPath(
      "M370 92c26 41 26 94-1 135l-2 3c-3 5-10 8-16 7l-59-6c44-33 72-84 78-139z",
      "lightgray"
    );
    this.backGlass = new FillPath(
      "M150 88v142l-41 6c-7 2-14-2-18-8l-9-18c-18-32-18-70 0-102l9-18c4-6 11-10 18-8z",
      "white"
    );
    this.backGlassShadow = new FillPath(
      "M91 228l-5-9c31-35 53-76 64-121v132l-41 6c-7 2-14-2-18-8z",
      "lightgray"
    );
    this.light = new FillPath(
      "M411 72l53 36-10 15-53-36zm43 124l10 15-54 35-10-15z",
      "yellow"
    );
  }

  draw(ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.scale(0.1, 0.1);
    ctx.rotate(this.angle);
    this.mirror.draw(ctx);
    this.back.draw(ctx);
    this.backShadow.draw(ctx);
    this.forwardGlass.draw(ctx);
    this.forwardGlassShadow.draw(ctx);
    this.backGlass.draw(ctx);
    this.backGlassShadow.draw(ctx);
    this.light.draw(ctx);
    ctx.restore();
  }

  canMove(point, crossRect, tl, mans) {
    if (!crossRect && !tl) return true;
    if (isInRect(this, crossRect, 50))
      return mans.every((m) => !isInRect(m, crossRect, 10));

    if (isInRect(point, crossRect, 50))
      return !tl.canWalk() && mans.every((m) => !isInRect(m, crossRect, 10));

    return true;
  }
  move(crossRect, tl, mans) {
    for (var i = 0; i < this.stepInFrame; i++) {
      var point = this.path.getPointAtLength(this.currentMove + 1);

      if (!this.canMove(point, crossRect, tl, mans)) {
        return;
      }
      this.currentMove = (this.currentMove + 1) % this.total;
      this.x = point.x;
      this.y = point.y;

      if (this.currentMove + 1 <= this.total) {
        var posAhead = this.path.getPointAtLength(this.currentMove + 1);
        this.angle = Math.atan2(posAhead.y - point.y, posAhead.x - point.x);
      } else {
        var posBehind = this.path.getPointAtLength(this.currentMove - 1);
        this.angle = Math.atan2(point.y - posBehind.y, point.x - posBehind.x);
      }
    }
  }
}


function createMovePath(path) {
  let p = document.createElementNS("http://www.w3.org/2000/svg", "path");
  p.setAttribute("d", path);
  return p;
}

function isInRect(point, rect, gap) {
  return point.y >= rect.y - gap && point.y <= rect.y + rect.height + gap &&
    point.x >= rect.x - gap && point.x <= rect.x + rect.width + gap;
}
html,
body {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
}

canvas {
  max-width: 100%;
  max-height: 100%;
}
<canvas id="canvas" width="1600" height="900"></canvas>

более структурированная версия

3
  • ♦ Классный ответ, круто! (+++) Странно, что никто не обратил внимание на него за 17 часов. А я пришел поздно (дела..) Я могу принять ответ, если ты его не будешь дальше улучшать Основная задача, которая есть в вопросе, пока не решена. Машинка должна не программно, по алгоритму зашитому в JS перемещаться, а именно интерактивно с помощью вращения колёсика мышки 7 апр 2022 в 13:16
  • @Alexandr_TT, вращение колесика не могу сделать, не на чем проверить, могу например по нажатию кнопки вперед, типа "газ"
    – Grundy
    7 апр 2022 в 13:52
  • ♦ Ну давай попробуем Сделай только пожалуйста отдельным ответом, чтобы старый вариант не терять 7 апр 2022 в 14:09

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.