dir.by  
  Search  
Programming, development, testing
Html & CSS
HTML <canvas> we draw a picture and text
  Looked at 3416 times    
 HTML <canvas> we draw a picture and text 
last updated: 16 Augusta 2020
В примере картинка и текст рисуются вот так на экране:
Code. Create a new 1.html file
  Html     Let's write the code in the file 1.html
<html>

<!-- heading -->
<head>
     <meta charset="utf-8">
     <title>Example</title>
</head>

<!-- page -->
<body>
     <!-- HTML canvas -->
     <canvas id="canvas1" width='400px' height='300px'></canvas>

     <!-- JavaScript Functions -->
     <script>

          // we upload pictures from files
          function loadImages(files, callbackAllFilesLoaded)
          {
               // count the number of files
               var countFilesToLoad = 0;
               for (var fileId in files)
               {
                    countFilesToLoad++;
               }

               var images = {};
               for (var fileId in files)
               {
                    // create a blank picture
                    images[fileId] = new Image();

                    // event onload
                    images[fileId].onload = function()
                    {
                         // when all the files are loaded, call our function callbackAllFilesLoaded to draw a picture
                         if ( --countFilesToLoad <= 0 )
                         {
                              callbackAllFilesLoaded(images);
                         }
                    };

                    // uploading a picture
                    images[fileId].src = files[fileId];
               }
          }

          // drawing a picture on canvas
          function MyDrawImage(context, image, x, y)
          {
               // drawing a picture
               context.drawImage(image, x, y);
          }

          function MyDrawText(context, text, color, font, x, y)
          {
               context.font = font;
               context.fillStyle = color;
               context.fillText(text, x, y);
          }
     </script>

     <!-- master code -->
     <script>

          <!-- Files -->
          var files = {
               tree : "./tree.jpg"
          };
    
          <!-- context for drawing -->
          var canvas = document.getElementById('canvas1');
          var context = canvas.getContext('2d');

          <!-- uploading a picture -->
          loadImages(files, function (loadedImages)
          {
               <!-- drawing a picture -->
               MyDrawImage(context, loadedImages.tree, 80, 20);

               <!-- drawing text -->
               MyDrawText(context, "Hello", "blue", "40pt Calibri", 150, 50);
               MyDrawText(context, "world!", "green", "20pt Calibri", 150, 80);
          });
     </script>
</body>

</html>
Скачиваем картинку

Picture tree.jpg must be in the same folder as the file 1.html
 
← Previous topic
HTML <canvas> draw a picture with horizontal reflection
 
Next topic →
HTML <canvas> draw a picture many times in a rectangle (template)
 
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  
Яндекс.Метрика