I use the same code to find the position of the mouse relative to a specific element (in this case, HTML5 canvas). It works on the mouse down, but it breaks on the mouse. How can I make it work with the mouse?
<!DOCTYPE html> <html> <body> <h1>This is page one; here we will play with HTML5</h1> <a href= "../index.html">This link takes you back to home</a> <div> <canvas onmousedown="mouseDown()" onmouseup="mouseUp()" id="myCanvas" width="1600" height="800" style="border:1px solid #000000;"> </canvas> </div> <script type="text/javascript"> var rect1x = rec1y; var a = b; function mouseDown() { a = document.getElementById("myCanvas").getBoundingClientRect().left; b = document.getElementById("myCanvas").getBoundingClientRect().top; rect1x = window.event.clientX - a; rect1y = window.event.clientY - b; } function mouseUp() { var rect2x = window.event.clientX - a; var rect2y = window.event.clientY - b; var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="#FF0000"; ctx.fillRect(rect1x,rect1y,rect2x,rect2y); } </script> <center><font size=1>Draw!</font></center> </body> </html>
ctx.fillRect accepts x, y, width, height , not x1, y1, x2, y2
ctx.fillRect
x, y, width, height
x1, y1, x2, y2
change this last line to:
ctx.fillRect(rect1x, rect1y, rect2x - rect1x, rect2y - rect1y);
Source: https://habr.com/ru/post/1438441/More articles:Data-Context-Interaction (DCI) and programmable event in javascript - javascriptpython mapping function acting on a string of numbers - pythonCropping images to any shape Android - androidAdd subdocument array element to subdocument array element in mongoDB - mongodbopen line of line of line using meta tag - htmlShopping Cart Magento - magentoiPhone - keyboard key - ioscut / copy / paste function stopped working in my iOS application - iosDjango user does not work when creating profile fields. - djangoStatus message damages main window in iPhone app - iosAll Articles