Search code examples
htmlcanvasfill

html canvas resolution issue with overlaying boxes


I have noticed issues with drawing one box over another. As requested, here is the code, but in greater detail

function draw(x,y,w,h,c){
 ctx.fillStyle=c;
 ctx.strokeStyle=c;
 ctx.lineWidth=1;
 ctx.globalAlpha=1.0;
 ctx.fillRect(x,y,w,h);
}

function Rectangle(x,y,w,h,c){
 this.x=x;
 this.y=y;
 this.w=w;
 this.h=h;
 this.c=c;
 this.draw=draw;

 this.onMouseEnter=function(){
  this.c='rgb(0,0,0)';   //black
  this.draw();
 }

this.onMouseLeave=function(){
 this.c='rgb(255,255,255)';   //white
 this.draw();
 }
}
box=new Rectangle(10,10,110,110,'rgb(255,255,255)');  //black box at

At rest the box is white, but on hover, it turns black. However, there is still a white border. I am pretty sure this is not a calculation error on my part as I am changing the color, not the dimensions. I have also noticed this problem occurring in most of my other onHover functions.

Why does HTML have these problems with drawing over other objects.

Thanks


Solution

  • This can often happen if you're creating the rect with non-int values. See http://jsfiddle.net/cwolves/9tZTy/

    If you change the numbers to non-integers (e.g. 25.5), you'll see that the box has a red "glow" around it when you click on the canvas.

    Simple solution is to floor every value you pass to fillRect:

    ctx.fillRect(x1 << 0, y1 << 0, x2 << 0, y2 << 0);
    

    [edit]

    Your example seems to be using ints, so if you still see the issue in my demo, call clearRect() first.