Home >Web Front-end >HTML Tutorial >html5 1px problem and method of drawing coordinate system grid

html5 1px problem and method of drawing coordinate system grid

一个新手
一个新手Original
2017-10-19 10:06:072293browse

In canvas, you need to draw a 1px line, which is not possible by default

context.beginPath();
                context.moveTo( 100, 100 );
                context.lineTo( 400, 100 );
                context.closePath();
                context.stroke();
                context.beginPath();
                context.strokeStyle = 'red';
                context.moveTo( 100.5, 200.5 );
                context.lineTo( 400.5, 200.5 );
                context.closePath();
                context.stroke();

In the above code, context is the context of canvas. In this code, I drew 2 lines, The upper line is not 1px, the lower line is 1px

You may not be able to see clearly above, whether the black line is 1px, you can Put them in drawing software or photoshop, zoom in, and then open the coordinates, you can see the following effect:

Obviously, this black line occupies 2 The line is 2px in size, and the red line occupies one line, which is the real 1px line segment. That is to say, in canvas, if you need to draw a 1px line segment, then add 0.5 after the coordinates, then, next, Let’s draw a coordinate system. The scale of the coordinate system in the x and y directions is 10px.


drawGrid('#09f', 10, 10);
            function drawGrid(color, stepx, stepy) {
                context.save()

                context.strokeStyle = color;
                context.lineWidth = 0.5;
                context.clearRect(0, 0, context.canvas.width, context.canvas.height);

                for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {
                    context.beginPath();
                    context.moveTo(i, 0);
                    context.lineTo(i, context.canvas.height);
                    context.stroke();
                }

                for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {
                    context.beginPath();
                    context.moveTo(0, i);
                    context.lineTo(context.canvas.width, i);
                    context.stroke();
                }

                context.restore();
            }

The above is the detailed content of html5 1px problem and method of drawing coordinate system grid. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn