画布圆看起来模糊

2 html javascript jquery canvas

这是对一些过时或不同问题的更新,例如:

我想画一条线,在这条线的末尾应该有一个圆,以生成一条圆线。

因为圆线末端应该在线条的一侧,所以我没有使用line-cap属性

在我的计算机上使用下面的代码可以正常工作,但可以在iPhone上测试该代码...该行看起来-让说好-来使圆圈看起来像废话: 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();
Run Code Online (Sandbox Code Playgroud)
<div style="position: absolute; margin-left: 25%;display: table; align-self: center; width: 100%;">
    <canvas id="canvas"></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我找不到有效的答案。但是如果有人能够解决我的问题,我将非常高兴。提前致谢。

Tim*_*ief 7

您的iPhone与PC的设备像素比例不同。画布将无法以与显示时相同的分辨率进行渲染,然后会显得模糊。

您必须为画布设置一个css大小,然后将此大小设置window.devicePixelRatio为画布的大小。最后按比例缩放画布坐标系,window.devicePixelRatio以获得完美的像素渲染。

(本文有助于进一步解释https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio

画布在视网膜屏幕上可能显得太模糊。使用window.devicePixelRatio确定应添加多少额外的像素密度以使图像更清晰。

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);
Run Code Online (Sandbox Code Playgroud)