I draw two images. One says "1x10" the other "10x10". Basically, I just draw a square divided by 9 vertical lines or the same square divided by 9 horizontal and 9 vertical lines when the user clicks over the images. Code as follows:
canvas.addEventListener('click',ProcessClick,false);
function ProcessClick(toi){
var posx = toi.layerX;
var posy = toi.layerY;
if(toi.layerX == undefined || toi.layerY == undefined){
posx = toi.offsetX;
posy = toi.offsetY;
}
if(posx>170 && posx<320 && posy>320 && posy<370){
rect1x10();
}
if(posx>470 && posx<620 && posy>320 && posy<370){
rect10x10();
}
}//ProcessClick
rect1x10 = function(){
ctx.strokeStyle = "blue";
ctx.fillStyle = "white";
ctx.clearRect(200, 375, 355, 325);
ctx.rect(240, 390, 300, 300);
ctx.fill();
ctx.lineWidth = 2;
ctx.stroke();
ctx.lineWidth = 1;
var lineX = 270.5;
for (i = 0; i <= 8; i++){
ctx.beginPath();
ctx.moveTo(lineX, 390);
ctx.lineTo(lineX, 690);
ctx.stroke();
lineX += 30;
}
}//rect1x10
rect10x10 = function(){
ctx.strokeStyle = "blue";
ctx.fillStyle = "white";
ctx.clearRect(200, 375, 355, 325);
ctx.rect(240, 390, 300, 300);
ctx.fill();
ctx.lineWidth = 2;
ctx.stroke();
ctx.lineWidth = 1;
var lineX = 270.5;
for (i = 0; i <= 8; i++){
ctx.beginPath();
ctx.moveTo(lineX, 390);
ctx.lineTo(lineX, 690);
ctx.stroke();
lineX += 30;
}
var lineY = 420.5;
for (i = 0; i <= 8; i++){
ctx.beginPath();
ctx.moveTo(240, lineY);
ctx.lineTo(540, lineY);
ctx.stroke();
lineY += 30;
}
}//rect10x10
All works fine (thin lines, well spaced) the first time either image is clicked, problem is when either rectangle is drawn, the next one acts up. For example: 1) When the 1x10 is called first and then 10x10 the last vertical line is thicker. 2) When the 10x10 is called first and then 1x10 the last horizontal line doesn't get erased at all. If I call 1x10 again the last horizontal line now gets erased but the last vertical line gets thicker.
All this is just a graphical reference, so I could easily display an image of a square divided as 1x10 or 10x10 and problem solved. However, I REALLY want to learn what I am doing wrong for future reference. Thanks in advance for all support.
You're getting a remnant of one of your paths when you stroke
the rectangles.
call ctx.beginPath();
before calling rect
.
Or, alternatively, skip all that and use strokeRect
ctx.beginPath();
ctx.rect(240, 390, 300, 300);
ctx.lineWidth = 2;
ctx.stroke();
ctx.lineWidth = 1;
or
ctx.clearRect(200, 375, 355, 325);
ctx.lineWidth = 2;
ctx.strokeRect(240, 390, 300, 300);
ctx.lineWidth = 1;