HTML canvas系列-画线模糊问题(8)
1、devicePixelRatio
devicePixelRatio 返回当前显示设备的物理像素分辨率与 CSS 像素分辨率的比率。这个属性使得浏览器确定使用多少个屏幕的实际像素来绘制单个 CSS 像素。
canvas使用 window.devicePixelRatio 以确定应该添加多少额外的像素得到清晰的图像。
2、scale方法
canvas缩放方法。
3、示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>绘制模糊问题</title>
</head>
<body>
<!-- 定义canvas元素 -->
<canvas id="chart" width="450" height="200" style="border: 1px solid black;"></canvas>
<script>
//创建上下文
var canvas = document.getElementById('chart');
//获取devicePixelRatio
var dpr = window.devicePixelRatio || 1;
//注意如下代码
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
canvas.width = canvas.width * dpr;
canvas.height = canvas.height * dpr;
var ctx = canvas.getContext('2d');
//注意如下代码
ctx.scale(dpr, dpr);
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = 'black';
ctx.moveTo(50, 50);
ctx.lineTo(250, 50);
ctx.stroke();
</script>
</body>
</html>


本文探讨了HTML5 Canvas中画线模糊的问题,通过利用devicePixelRatio获取设备像素比,并结合scale方法调整画布比例,实现清晰的画线效果。文章提供了一个示例来说明这两个属性的用法。
1069

被折叠的 条评论
为什么被折叠?



