dir.by  
  Search  
Programming, development, testing
Html & CSS
HTML <canvas> drawing a snake with lines moveTo, lineTo
  Looked at 3003 times    
 HTML <canvas> drawing a snake with lines moveTo, lineTo 
last updated: 15 Augusta 2020
Example we look, we test

Code. Create a new 1.html file
  Html     Let's write the code in the file 1.html
<html>

<!-- заголовок -->
<head>
<meta charset="utf-8">
<title>Example</title>
</head>

<!-- страница -->
<body>

     <!-- HTML canvas -->
     <canvas id="canvas1" width='530px' height='320px' style='border: 1px solid #9C9898;'></canvas>

     <!-- JavaScript Functions -->
     <script>
          function AnimationInit()
          {
               window.requestAnimFrame = (function(callback) {
                    return window.requestAnimationFrame ||
                         window.webkitRequestAnimationFrame ||
                         window.mozRequestAnimationFrame ||
                         window.oRequestAnimationFrame ||
                         window.msRequestAnimationFrame ||
                         function(callback)
                         {
                              window.setTimeout(callback, 1000 / 60); // 60 time in 1 second (1000 ms)
                         };
               })();
          }

     </script>

     <!-- master code -->
     <script>
          function getRandTheta(){
               return Math.random() * 2 * Math.PI;
          }

          function updateSnake(canvas, snake)
          {
               var maxVariance = 0.2;
               var snakeSpeed = 200; //px / s
               var segmentsPerSecond = snakeSpeed / snake.segmentLength;
               var segments = snake.segments;
               var date = new Date();
               var time = date.getTime();
               var timeDiff = (time - snake.lastUpdateTime);

               if (timeDiff > 1000 / segmentsPerSecond)
               {
                    var head = segments[segments.length - 1];
                    var neck = segments[segments.length - 2];

                    var direction = snake.direction;
                    var newHeadX = head.x + direction.x * snake.segmentLength;
                    var newHeadY = head.y + direction.y * snake.segmentLength;

                    // change direction if collision occurs
                    if (newHeadX > canvas.width || newHeadX < 0)
                    {
                         direction.x *= -1;
                    }
                    if (newHeadY > canvas.height || newHeadY < 0)
                    {
                         direction.y *= -1;
                    }

                    // add new segment
                    segments.push({
                         x: newHeadX,
                         y: newHeadY
                    });

                    if (segments.length > snake.numSegments) {
                         segments.shift();
                    }

                    var variance = ((maxVariance / 2) - Math.random() * maxVariance);

                    direction.x += variance;
                    direction.y -= variance;

                    // update direction vector
                    if (direction.x > 1) {
                         direction.x = 1;
                    }
                    if (direction.x < -1) {
                         direction.x = -1;
                    }

                    // dampering - try to keep direction vectors around -0.5 and +0.5
                    direction.x *= Math.abs(direction.x) > 0.5 ? (1 - 0.01) : (1 + 0.01);
                    direction.y *= Math.abs(direction.y) > 0.5 ? (1 - 0.01) : (1 + 0.01);

                    snake.lastUpdateTime = time;
               }
          }

          function drawSnake(context, snake)
          {
               var segments = snake.segments;
               var tail = segments[0];
               context.beginPath();
               context.moveTo(tail.x, tail.y);

               for (var n = 1; n < segments.length; n++)
               {
                    var segment = segments[n];
                    context.lineTo(segment.x, segment.y);
               }

               context.lineWidth = 10;
               context.lineCap = "round";
               context.lineJoin = "round";
               context.strokeStyle = "green";
               context.stroke();
          }

          function MyAnimation(context, canvas, loadedImages, snake)
          {
               <!-- clear everything on canvas -->
               context.clearRect(0, 0, canvas.width, canvas.height);
         
               // Draw
               drawSnake(context, snake);

               // change position
               updateSnake(canvas, snake);
         
               // request new frame
               requestAnimFrame(function(){
                    MyAnimation(context, canvas, loadedImages, snake);
               });
          }

          <!-- context for drawing -->
          var canvas = document.getElementById('canvas1');
          var context = canvas.getContext('2d');

          <!-- initializing an animation -->
          AnimationInit();

          <!-- data -->
          var segmentLength = 2; // px
          var headX = canvas.width / 2;
          var headY = canvas.height / 2;

          snake = {
               segmentLength: 2,
               lastUpdateTime: 0,
               numSegments: 50,
               // moving to the right
               direction: {
                    x: 1,
                    y: 0
               },
               segments: [{
                    // tail
                    x: headX + segmentLength,
                    y: headY
               }, {
                    // head
                    x: headX,
                    y: headY
               }]
          };

          <!-- start endless animation -->
          MyAnimation(context, canvas, null, snake);

     </script>
</body>

</html>
 
← Previous topic
HTML <canvas> how to get mouse coordinates ? Determine the position of the mouse.
 
Next topic →
CSS description
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
HTML elements
HTML tag <a> link to go to another page
HTML tag <abbr> shows an abbreviated name, if you let the mouse down there will be a pop-up inscription
HTML tags fieldset and legend. This is a frame with a title
HTML tag <!-- --> comment
style="border" in the HTML

HTML поиск элемента, элементов
document.querySelector(...) это JavaScript метод для поиска элемента из document (то есть во всем HTML)
yourElement.querySelectorAll(...) это JavaScript метод для поиска элементов внутри другого HTML элемента

HTML svg (vector graphics for drawing lines, rectangles, ellipses, ...)
<svg> vector graphics, drawing a line<line>, rectangle <rect>, circle<circle>, text<text>

HTML canvas (drawing pictures, text, shapes)
HTML <canvas> drawing a rectangle
HTML <canvas> рисуем линии по нажатию мышкой на Canvas
HTML <canvas> we draw pictures
HTML <canvas> we draw a picture with a rotation
HTML <canvas> draw a picture with horizontal reflection
HTML <canvas> we draw a picture and text
HTML <canvas> draw a picture many times in a rectangle (template)
HTML <canvas> how to get mouse coordinates ? Determine the position of the mouse.
HTML <canvas> drawing a snake with lines moveTo, lineTo
CSS
CSS description
After modifying the file css , the browser displays old styles over and over again. Why?
Books to study CSS
CSS flex (элемент может растягиваться или сжиматься и таким образом заполнять свободное пространство)
Что такое CSS flex
Freeze
Шапка в таблице всегда видна при скролинге | freeze header in table | HTML
Div всегда виден при скролинге (position:fixed, position:sticky) | freeze div | HTML
Do Popup using HTML and Javascript
How to make a Popup window in a HTML page | Javascript, HTML, CSS
Motion and animation of pictures
Анимация человечка на месте. Используем HTML элемент <div>. Для анимации используем CSS стили: "animation", "background-image", "background-position", "keyframes"
Анимация человечка в движении (sprite). Используем HTML элементы <div>, <img>. Для анимации используем CSS стили: "animation", "background-image", "background-position", "keyframes"
Рисуем картинку с движением. Используем HTML элемент <canvas>. Для движения используем JavaScript: var img = new Image(), img.src = url, drawImage, timer, window.setInterval
Drawing a picture with movement and animation (sprite). Используем HTML элемент <canvas>. Для движения используем JavaScript: var img = new Image(), img.src = url, drawImage, timer, window.setInterval
Web страница на телефоне
Открываю web страницу на телефоне в Google Chrome. Почему при двойном нажатии размер страницы увеличивается?
Верстка, дизайн страницы
What the Front-end development?
Как определить устройство (планшет, компьютер, телефон) сейчас используется в JavaScript, HTML
Как сделать чтобы ваш сайт работал на телефоне, планшете, компьютере используем css media и max-device-width и min-device-width | HTML | CSS
How to make your website fit in size on your phone, tablet? (HTML meta with attribute name='viewport')
Correct layout HTML. Bad to use table. You need to use div
Что такое Adaptive design (адаптивный дизайн)? Что такое Responsive design (отзывчивый дизайн) ?
Меняем цвет scrollbar (полосы прокрутки) для HTML страницы. Используем CSS
WWW sites for learning
Sites to explore HTML

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика