Solution to inconsistent border styles when drawing rectangles in HTML5 canvas

Time:2022-8-2

In these two days, I need to use my colleague HTML5 to draw pictures. I found that the borders drawn by the functions that draw rectangles inside are inconsistent in style. Finally, I found the crux of the problem through some elimination methods, and now I share it with you.

First attach the code of HTML5 drawing rectangle:

Copy code

The code is as follows:

<canvas width=”578″ height=”200″></canvas>
<script>
var canvas = document.getElementById(‘myCanvas’);
var context = canvas.getContext(‘2d’);

context.beginPath();

context.rect(188.0, 50, 200, 100.375);
context.fillStyle = ‘white’;
context.fill();
context.lineWidth = 1;
context.strokeStyle = ‘red’;
context.stroke();
</script>

You will find that the border style is different after implementation, and the bottom is obviously very thin. The color is also slightly different

After changing context.rect (188.0, 50, 200, 100.375) to context.rect (188.0, 50, 200, 100), it is found that the style is completely consistent.
This shows that when drawing a rectangle, if the parameters inside are not integers, it is easy to cause border problems, so it is recommended that you round it up and then use it again.

Recommended Today

Use of String

1. Use of String String s1 = “abc”;//How literals are defined String s2 = “abc”; System.out.println(s1==s2)//true, s1, s2 point to the same address   1. String is declared final and cannot be inherited2. The String class implements the Serializable interface: indicating that strings support serialization,Implements the Comparable interface: indicates that String can be compared in […]