4

This is an update to some outdated or different questions like:

I'd like to draw a line and at the end of this line there should some kind of a circle to generate a rounded line.

Because the round-lineend should be just at one side of the line I didn't use the line-cap property.

Using this code below on my computer works fine but testing this code with my iPhone... The line looks -lets say OK- to tbh the circle looks just like crap: Super blurry!

img

var c=document.getElementById("canvas");
var ctx=c.getContext("2d");

ctx.strokeStyle = "red"
ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineWidth = 10;
ctx.lineTo(50,100);
ctx.stroke();
ctx.beginPath();
ctx.arc(50, 100, 0.001, 0, 2 * Math.PI, false);
ctx.lineWidth = 10;
ctx.strokeStyle = "green"
ctx.stroke();
<div style="position: absolute; margin-left: 25%;display: table; align-self: center; width: 100%;">
    <canvas id="canvas"></canvas>
</div>

I couldn't find an working answer so far. But I would be super happy if somebody could fix my problem. Thanks in advance.

2 Answers2

14

Your iPhone does not have the same device pixel ratio as your PC. The canvas will not render at the same resolution as it is displayed, and then can appear blurry.

You have to set a css size to your canvas, then, set this size times window.devicePixelRatio as the size of the canvas. Finally scale your canvas coordinate system by a factor window.devicePixelRatio to have a pixel perfect rendering.

(this article can help for further explanation https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio)

A canvas can appear too blurry on retina screens. Use window.devicePixelRatio to determine how much extra pixel density should be added to allow for a sharper image.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// Set display size (css pixels).
var size = 200;
canvas.style.width = size + "px";
canvas.style.height = size + "px";

// Set actual size in memory (scaled to account for extra pixel density).
var scale = window.devicePixelRatio; // <--- Change to 1 on retina screens to see blurry canvas.
canvas.width = size * scale;
canvas.height = size * scale;

// Normalize coordinate system to use css pixels.
ctx.scale(scale, scale);
Tim Krief
  • 354
  • 2
  • 10
0

how about this?

var c=document.getElementById("canvas");
var ctx=c.getContext("2d");

ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineWidth = 10;
ctx.lineTo(50,100);
ctx.closePath();
ctx.stroke();

ctx.beginPath();
ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = "green";
ctx.fill();
ctx.closePath();
<div style="position: absolute; margin-left: 25%;display: table; align-self: center; width: 100%;">
    <canvas id="canvas"></canvas>
</div>
Overcl9ck
  • 828
  • 7
  • 11