HTML5 Canvas Draw Rect - Got Diff Width Border?

The result of the square border turns out to be different widths, it seems that the right and lower borders of a width of 2x are wider than the left and upper borders. Why is it so strange? I want the border of all sides to be the same width.

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML5 Test</title> <script type="text/javascript"> function draw () { var canvas = document.getElementById('rectangle'); var ctx = canvas.getContext('2d'); ctx.save(); ctx.lineWidth = 30; ctx.fillStyle = "black"; ctx.fillRect(0,0,100,100); ctx.strokeStyle = "red"; ctx.strokeRect(0,0,100,100); ctx.restore(); } </script> </head> <body onload="draw()"> <canvas id="rectangle"></canvas> </body> </html> 

enter image description here

+8
javascript html5 html5-canvas
source share
1 answer

This is because your border is trimmed at the top and left, because where the canvas starts, and if your rectangle starts with (0,0), the coordinate of the left x axis will be -30.

Make the starting coordinates something above 30 (so that the end of your borders is not negative), and it will work fine.

Demo

+7
source share

All Articles