简体   繁体   中英

HTML5 Canvas antialias

The Example .

Hello every body. I have a Canvas with red background. On it I have rows of boxes, which go exactly after each other. Each box begins exactly where previous box ends, and they all have same skew. So there should not be any gap between edges, but as you can see in the example there are gaps.

Does anybody knows why is this happening, and how to get rid of it.

 console.clear(); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var world = { centerY: canvas.height / 2, centerX: canvas.width / 2 } var rowCount = 14; var box = { width: 20, height: 20, skew: 10 } function drawBox(x, y, id) { ctx.save(); ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + box.width, y); ctx.lineTo(x + box.width + box.skew, y - 20); ctx.lineTo(x + box.skew, y - box.height); ctx.lineTo(x, y); ctx.closePath(); ctx.clip(); ctx.clearRect(0,0, canvas.width, canvas.height); ctx.fillStyle = id % 2 == 0 ? 'lightgray' : 'darkgray'; ctx.fill(); ctx.restore(); } for (var i = 0; i < 112; i++) { var k = Math.floor(i / rowCount) * rowCount; console.log(k); drawBox(i * box.width - (k * box.width), Math.floor(i / rowCount) * box.height, i) } 
 #canvas { background-color: red; width: 800px; height: 600px; } 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <canvas id="canvas"> </canvas> </body> </html> 

In function drawBox Updated:

  ctx.lineTo(x+box.width, y);
  ctx.lineTo(x+box.width + box.skew, y - 20);

To

ctx.lineTo(x+box.width+1, y);
ctx.lineTo(x+box.width + box.skew +1, y - 20);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM