Reputation: 1
how are you? I'm struggling with a little problem I have with my code. I'm asked to create a paint program with javascript and I'm almost there but I'm struggling with how fast it paints. I have it painting so that it draws something on every mouseDrag event at clients x and y position.
See how the sample paint's shapes are defined and you can see each one, here is my program after drawn on canvas.
Here is mine, it paints way too fast.
if(dragging && type.options[type.selectedIndex].value == "squares") {
ctx.lineTo(e.clientX, e.clientY);
ctx.lineWidth = 5;
ctx.beginPath();
ctx.rect(e.clientX, e.clientY, 40, 40);
ctx.fill();
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.moveTo(e.clientX, e.clientY);
}
Upvotes: 0
Views: 233
Reputation: 2255
You could save the time of each draw and whenever you would potentially draw again, check if enough time has passed since the last paint.
Here is an example:
const ctx = document.getElementById('canvas').getContext('2d');
const speedInput = document.getElementById('draw-speed');
let buffer = +speedInput.value;
let lastPaint;
ctx.canvas.onmousemove = ({ x, y }) => {
const now = Date.now();
if (!lastPaint || (now - lastPaint) > buffer) {
lastPaint = now;
ctx.fillRect(x, y, 10, 10);
}
};
speedInput.onchange = ({ target }) => {
buffer = +target.value;
};
canvas {
border: 1px solid black;
}
label {
display: block;
}
<canvas id="canvas"></canvas>
<label for="draw-speed">Draw speed</label>
<select id="draw-speed">
<option>0</option>
<option>50</option>
<option selected>100</option>
<option>150</option>
</select>
Upvotes: 2