Advertisement
asimryu

canvas draw rectangle

Jul 10th, 2020
1,425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.89 KB | None | 0 0
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>Coding Canvas</title>
  5. <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>
  6. <style>
  7.     canvas {border: 1px solid #000;}
  8. </style>
  9. </head>
  10. <body>
  11.     <canvas id="canvas" width="800" height="500"></canvas>
  12.     <div id="output"></div>
  13. <script>
  14.     //Canvas
  15.     var canvas = document.getElementById('canvas');
  16.     var ctx = canvas.getContext('2d');
  17.     //Variables
  18.     var canvasx = $(canvas).offset().left;
  19.     var canvasy = $(canvas).offset().top;
  20.     var last_mousex = last_mousey = 0;
  21.     var width = height = 0;
  22.     var mousex = mousey = 0;
  23.     var mousedown = false;
  24.  
  25.     //Mousedown
  26.     $(canvas).on('mousedown', function(e) {
  27.         last_mousex = parseInt(e.clientX-canvasx);
  28.         last_mousey = parseInt(e.clientY-canvasy);
  29.         mousedown = true;
  30.     });
  31.  
  32.     //Mouseup
  33.     $(canvas).on('mouseup', function(e) {
  34.         mousedown = false;
  35.         ctx.beginPath();
  36.         ctx.clearRect(0,0,canvas.width,canvas.height);
  37.         ctx.beginPath();
  38.         ctx.rect(last_mousex,last_mousey,width,height);
  39.         ctx.fillStyle = "red";
  40.         ctx.fill();
  41.        
  42.     });
  43.  
  44.     //Mousemove
  45.     $(canvas).on('mousemove', function(e) {
  46.         mousex = parseInt(e.clientX-canvasx);
  47.         mousey = parseInt(e.clientY-canvasy);
  48.         if(mousedown) {
  49.             ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas
  50.             ctx.beginPath();
  51.             width = mousex-last_mousex;
  52.             height = mousey-last_mousey;
  53.             ctx.setLineDash([6]);
  54.             ctx.rect(last_mousex,last_mousey,width,height);
  55.             ctx.strokeStyle = 'black';
  56.             ctx.lineWidth = 5;
  57.             ctx.stroke();
  58.         }
  59.         //Output
  60.         $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
  61.     });
  62. </script>
  63.  
  64.  </body>
  65. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement