Terminal
Terminal

Reputation: 123

HTML Canvas - How to draw very thin lines?

I have created a project using the JavaScript library P5.js and used its built-in line() and ellipse() functions to draw lines and circles to a canvas. I am now attempting to remove the entirety of P5.js and its functions from my project to leave pure JavaScript however when I replace P5s line and ellipse functions with JavaScripts ctx.LineTo and ctx.arc I do not get the same results.

The drawings created with the P5.js Library look much sharper and high resolution.

The image below was created using P5.js line() and ellipse() functions.

This image however, was created using pure JavaScript and as you can see it looks much worse.

Using pure JavaScript I have set the line width to be the thinnest possible however it still looks thicker and fuzzier than the P5.js version.

How can I draw lines using pure JavaScript exactly how the P5.js Library does to get the same sharp, crisp result?

The Javascript I am using currently is as follows:

ctx.beginPath();
ctx.moveTo(30, 40);
ctx.lineTo(60, 90);
ctx.strokeStyle = 'white';
ctx.lineWidth = 0.1;
ctx.stroke();

This question post was labelled as a duplicate of another question however the "duplicate" question does not solve my issue as I stated I have tried adding .5 onto to coordinate values that that doesn't work.

Upvotes: 4

Views: 3113

Answers (1)

Blindman67
Blindman67

Reputation: 54026

devicePixelRatio

The canvas is at the wrong resolution.Suspect you are using a retina or high resolution display. You need to match the canvas pixel size to the device pixel size, currently you are matching the CSS pixel size which for retina displays is 4 device pixels for each CSS pixel. Use devicePixelRatio global property to find CSS pixel size, then set the canvas resolution canvas.width = pixelWidth * devicePixelRatio same for height.

The following two answers are related to the same issue.

Upvotes: 4

Related Questions