javascript - Canvas 圈看起来模糊

标签 javascript jquery html canvas

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

我想画一条线,在这条线的末端应该有某种圆来生成一条圆线。

因为 round-lineend 应该就在线的一侧,所以我没有使用 line-cap 属性

在我的电脑上使用下面的这段代码工作正常,但用我的 iPhone 测试这段代码......这条线看起来 - 让我们说好的 - 说实话,圆圈看起来就像垃圾: super 模糊!

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>

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

最佳答案

您的 iPhone 的设备像素比与您的 PC 不同。 Canvas 不会以与显示时相同的分辨率呈现,然后会显得模糊。

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

(这篇文章可以帮助进一步解释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);

关于javascript - Canvas 圈看起来模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48961797/

相关文章:

javascript - HTML 客户端接收服务器输出数据的连续流

javascript - 陷入 onsubmit 的困境

jquery - 将悬停添加到 .live ('click' ,函数 ()

jquery - Dynatree .sortChildren

jquery - 侧边栏带有纯 CSS 的侧边距?

javascript - 添加 JavaScript 语句

html - 如何在 HTML 页面中放置标签

javascript - Withings API 不适用于 node-oauth

javascript - AJAX检查页面每5分钟返回一次

javascript - 如何根据单选按钮的选择启用/禁用表单上的多个提交按钮