Reputation: 148524
I have a simple canvas element :
<canvas id="floor" style="background-color:#f7f7f7;border:1px #000 solid;" >
</canvas>
I also have a draw
function which creates vertical/horizontal lines :
function draw(){
ctx.translate(0.25, 0.25);
for (var x = size; x < canvas.width; x += size) { //vertical
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
}
for (var y = size; y < canvas.height; y += size) { //horizontal
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
}
ctx.strokeStyle = "#C1C1C1";
ctx.stroke();
}
Result:
The button calls this draw
function again :
$(".b").on('click',function (){
draw();
})
But if I click this button many times, it seems that it adds more lines making it look thicker :
Question
Why doesn't the canvas look the same if I draw exactly the same lines?
And how can I fix my code to make it look the same?
Upvotes: 1
Views: 61
Reputation: 1575
You need to clear the canvas before redrawing the lines and use the context begin path method:
ctx.clearRect(0, 0, canvas.width, canvas.height);
var canvas = document.getElementById('floor');
var ctx = canvas.getContext("2d");
var size = 20
function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
//ctx.translate(0.25, 0.25);
//this is important!
ctx.beginPath();
for (var x = size; x < canvas.width; x += size) { //vertical
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
}
for (var y = size; y < canvas.height; y += size) { //horizontal
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
}
ctx.strokeStyle = "#C1C1C1";
ctx.stroke();
}
document.getElementById('button').addEventListener('click', draw);
<canvas id="floor" style="background-color:#f7f7f7;border:1px #000 solid;" >
</canvas>
<button id="button">
redraw
</button>
Upvotes: 1
Reputation: 262
On every call of draw
you need to start a new path with:
ctx.beginPath();
Upvotes: 2