I've written some code in JS that allows the user to click on the screen to create a square, and hold down the mouse to increase the size of the square before stamping it. The problem is that the speed at which the size of the square increases while the mouse is held down slows once the mouse is moved from the originally clicked position. I'm using intervals to change the size over a time of 1 millisecond. Here is the JS code (with Jquery):
UPDATE: If you run the code snippet you won't see the issue. Try saving it as a file and running it, then the issue will probably occur.
<!DOCTYPE html>
<html>
<head>
<title>My Canvas</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var mouseDown
var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");
var objects = []
c.addEventListener("mousedown", onMouseDown);
c.addEventListener("mouseup", onMouseUp);
function createSquare(x, y, size) {
this.x = x;
this.y = y;
this.size = size;
this.draw = draw;
this.drawStylus = drawStylus;
this.clear = clear;
};
function draw() {
ctx.fillRect(this.x, this.y, this.size, this.size);
};
function drawStylus() {
ctx.fillRect(this.x, this.y, this.size, this.size);
};
function clear() {
ctx.clearRect(this.x, this.y, this.size, this.size);
}
// var mySquare = new createSquare(100,100,100);
// mySquare.draw();
function onMouseDown() {
mouseDown = true
x = event.clientX
y = event.clientY
size = 100
console.log('clicked')
interval = setInterval(function () {
size = size + 5
var cursorSquare = new createSquare(x,y,size);
cursorSquare.clear();
cursorSquare.drawStylus();
}, 1);
};
function onMouseUp() {
console.log('up')
if (mouseDown) {
clearInterval(interval);
var newSquare = new createSquare(x,y,size);
newSquare.draw();
mouseDown = false
};
};
});
</script>
</head>
<body>
<canvas id='myCanvas' width="5000" height="5000" style="border:1px solid #000000;">
</canvas>
</body>
</html>