Reputation: 5156
I am trying to keep redrawing rectangles on HTML canvas as if I am selecting a specific region.
When I move my mouse pointer (while pressing down the mouse key) I call redraw
which clears the canvas and redraws a rectangle corresponding to the globally stored coordinates.
Since canvas is cleared for every mouse mouse event I expected to get only one rectangle in the canvas but I got too many rectangles.
Here is my code:
<canvas id="image" width="0" height="0" style="background-color: orange"></canvas>
<script>
var mousedown = false;
var x1;
var y1;
var x2;
var y2;
document.getElementById("image").onmousedown = function(e) {
mousedown = true;
x1 = e.offsetX;
y1 = e.offsetY;
console.log(e.offsetX);
console.log(e.offsetY);
var canvas = document.getElementById("image")
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
console.log('clean');
}
document.getElementById("image").onmouseup = function(e){
mousedown = false;
}
document.getElementById("image").onmousemove = function(e) {
if (mousedown) {
x2 = e.offsetX;
y2 = e.offsetY;
redraw()
}
}
function redraw() {
var canvas = document.getElementById("image")
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.rect(x1, y1, (x2 - x1), (y2 - y1));
context.stroke();
}
</script>
And the result is:
Why do I get so many rectangles and how can I get the last one? (Or how can I do it more efficiently without any libraries?)
Upvotes: 0
Views: 179
Reputation: 2049
Your problem is not on the clearRect method, the problem is that you need to begin a Path when you wish to draw on the canvas.
Add context.beginPath();
above context.rect();
Some great questions that have already been answered here:
clearRect not working
Also these articles are great for canvas manipulation: http://cheatsheetworld.com/programming/html5-canvas-cheat-sheet/ https://www.w3schools.com/tags/ref_canvas.asp
Upvotes: 1