Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <title></title>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <style>
- #myPics{
- width:100%;
- }
- </style>
- <script>
- // When true, moving the mouse draws on the canvas
- let isDrawing = false;
- let x = 0;
- let y = 0;
- document.addEventListener("DOMContentLoaded", function(){
- const myPics = document.getElementById('myPics');
- const context = myPics.getContext('2d');
- context.canvas.width = window.innerWidth;
- context.canvas.height = window.innerHeight;
- // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas.
- // Add the event listeners for mousedown, mousemove, and mouseup
- myPics.addEventListener('mousedown', e => {
- x = e.offsetX;
- y = e.offsetY;
- isDrawing = true;
- });
- myPics.addEventListener('mousemove', e => {
- if (isDrawing === true) {
- drawLine(context, x, y, e.offsetX, e.offsetY);
- x = e.offsetX;
- y = e.offsetY;
- }
- });
- window.addEventListener('mouseup', e => {
- if (isDrawing === true) {
- drawLine(context, x, y, e.offsetX, e.offsetY);
- x = 0;
- y = 0;
- isDrawing = false;
- }
- });
- });
- function drawLine(context, x1, y1, x2, y2) {
- context.beginPath();
- context.strokeStyle = 'black';
- context.lineWidth = 1;
- context.moveTo(x1, y1);
- context.lineTo(x2, y2);
- context.stroke();
- context.closePath();
- }
- </script>
- </head>
- <body>
- <h1>Drawing with mouse events</h1>
- <canvas id="myPics"></canvas>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement