JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Drawing with mouse events</h1>
<p id="fps">FPS </p>
<p id="fps_max">FPS Max </p>
<p id="counter">FPS Max </p>
<canvas id="myPics" width="560" height="360"></canvas>
CSS
canvas {
border: 1px solid black;
width: 560px;
height: 360px;
}
JavaScript
// When true, moving the mouse draws on the canvas
let isDrawing = false;
let x = 0;
let y = 0;
const myPics = document.getElementById('myPics');
const context = myPics.getContext('2d');
// 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;
});
var lastLoop = new Date();
var max_ = 0;
var count = 0;
myPics.addEventListener('mousemove', e => {
var fpsOut = document.getElementById('fps');
var fpsMaxOut = document.getElementById('fps_max');
var thisLoop = new Date();
var fps = Math.trunc(1000 / (thisLoop - lastLoop));
count++;
lastLoop = thisLoop;
fpsOut.innerHTML = fps + " fps";
max_ = Math.max(fps, max_);
fpsMaxOut.innerHTML = max_ + " fps";
if (isDrawing === true) {
drawLine(context, x, y, e.offsetX, e.offsetY);
x = e.offsetX;
y = e.offsetY;
}
});
setInterval(function(){
var counterOut = document.getElementById('counter');
counterOut.innerHTML = count
count = 0;
console.log("GGG");
}, 1000);
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();
}