Advertisement
metalx1000

HTML5/JavaScript Simple Canvas Draw

Jul 31st, 2020
2,452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <title></title>
  5.     <meta charset="utf-8">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">
  7.     <style>
  8.       #myPics{
  9.         width:100%;
  10.       }
  11.     </style>
  12.     <script>
  13.       // When true, moving the mouse draws on the canvas
  14.       let isDrawing = false;
  15.       let x = 0;
  16.       let y = 0;
  17.  
  18.       document.addEventListener("DOMContentLoaded", function(){
  19.  
  20.         const myPics = document.getElementById('myPics');
  21.         const context = myPics.getContext('2d');
  22.         context.canvas.width  = window.innerWidth;
  23.         context.canvas.height = window.innerHeight;
  24.  
  25.         // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.
  26.  
  27.         // Add the event listeners for mousedown, mousemove, and mouseup
  28.         myPics.addEventListener('mousedown', e => {
  29.           x = e.offsetX;
  30.           y = e.offsetY;
  31.           isDrawing = true;
  32.         });
  33.  
  34.         myPics.addEventListener('mousemove', e => {
  35.           if (isDrawing === true) {
  36.             drawLine(context, x, y, e.offsetX, e.offsetY);
  37.             x = e.offsetX;
  38.             y = e.offsetY;
  39.           }
  40.         });
  41.  
  42.         window.addEventListener('mouseup', e => {
  43.           if (isDrawing === true) {
  44.             drawLine(context, x, y, e.offsetX, e.offsetY);
  45.             x = 0;
  46.             y = 0;
  47.             isDrawing = false;
  48.           }
  49.         });
  50.       });
  51.  
  52.       function drawLine(context, x1, y1, x2, y2) {
  53.         context.beginPath();
  54.         context.strokeStyle = 'black';
  55.         context.lineWidth = 1;
  56.         context.moveTo(x1, y1);
  57.         context.lineTo(x2, y2);
  58.         context.stroke();
  59.         context.closePath();
  60.       }
  61.     </script>
  62.   </head>
  63.   <body>
  64.     <h1>Drawing with mouse events</h1>
  65.     <canvas id="myPics"></canvas>
  66.   </body>
  67. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement