Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE HTML>
- <html>
- <head>
- <title>Coding Canvas</title>
- <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>
- <style>
- canvas {border: 1px solid #000;}
- </style>
- </head>
- <body>
- <canvas id="canvas" width="800" height="500"></canvas>
- <div id="output"></div>
- <script>
- //Canvas
- var canvas = document.getElementById('canvas');
- var ctx = canvas.getContext('2d');
- //Variables
- var canvasx = $(canvas).offset().left;
- var canvasy = $(canvas).offset().top;
- var last_mousex = last_mousey = 0;
- var width = height = 0;
- var mousex = mousey = 0;
- var mousedown = false;
- //Mousedown
- $(canvas).on('mousedown', function(e) {
- last_mousex = parseInt(e.clientX-canvasx);
- last_mousey = parseInt(e.clientY-canvasy);
- mousedown = true;
- });
- //Mouseup
- $(canvas).on('mouseup', function(e) {
- mousedown = false;
- ctx.beginPath();
- ctx.clearRect(0,0,canvas.width,canvas.height);
- ctx.beginPath();
- ctx.rect(last_mousex,last_mousey,width,height);
- ctx.fillStyle = "red";
- ctx.fill();
- });
- //Mousemove
- $(canvas).on('mousemove', function(e) {
- mousex = parseInt(e.clientX-canvasx);
- mousey = parseInt(e.clientY-canvasy);
- if(mousedown) {
- ctx.clearRect(0,0,canvas.width,canvas.height); //clear canvas
- ctx.beginPath();
- width = mousex-last_mousex;
- height = mousey-last_mousey;
- ctx.setLineDash([6]);
- ctx.rect(last_mousex,last_mousey,width,height);
- ctx.strokeStyle = 'black';
- ctx.lineWidth = 5;
- ctx.stroke();
- }
- //Output
- $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement