【发布时间】:2017-09-01 16:35:48
【问题描述】:
我已阅读有关视网膜显示器上画布模糊问题的多项建议(例如,使用 window.devicePixelRatio 方法;here、here 和 here)但我无法应用针对我的具体问题提出了解决方案。下面的脚本首先创建一个带有一些随机图像数据(看起来很模糊)的画布,然后将图像导出到 SVG 元素并重新缩放它(当然仍然是模糊的)。我在 2016 年末使用带有触摸栏和 safari 的 MBP。关于如何避免模糊和实现清晰边缘的任何建议?请记住,初始 imageData 应具有固定的宽度和高度。
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<body></body>
<script type="text/javascript">
var width = 100;
var height = 100;
var canvas = d3.select("body").append("canvas");
context = canvas.node().getContext("2d"),
canvas
.attr("width", width)
.attr("height", height)
.style("width", width + "px")
.style("height", height + "px")
//this is the part that should normally take care of blurriness
if (window.devicePixelRatio > 1) {
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
var ratio = devicePixelRatio / backingStoreRatio;
canvas
.attr('width', width * ratio)
.attr('height', height * ratio)
.style('width', width + 'px')
.style('height', height + 'px');
context.scale(ratio, ratio);
}
var imageData = context.createImageData(width, height);
for (var i = 0, l = 0; i<height; ++i) {
for (j = 0; j<width; ++j, l += 4) {
imageData.data[l+0] = Math.round( Math.random() * 255);
imageData.data[l+1] = Math.round( Math.random() * 255);
imageData.data[l+2] = Math.round( Math.random() * 255);
imageData.data[l+3] = Math.round( Math.random() * 255);
}
}
context.putImageData(imageData, 0, 0);
var ImageD = canvas.node().toDataURL("img/png");
var svg = d3.select('body').append('svg').attr('width', width*5).attr('height', height*5);
svg.append("svg:image").datum(ImageD).attr("xlink:href", function(d) {return d})
.attr("height", height*5).attr("width", width*5)
</script>
【问题讨论】:
-
为什么您无法将建议的解决方案应用于您的具体问题?
-
好吧,上面的脚本实现了这些解决方案没有成功
-
Retina 将 CSS 像素设置为 2 个物理像素。画布分辨率设置为 CSS 像素。要修复将画布分辨率设置为画布大小的 2 倍。通过
const bounds = element.getBoundingClientRect();获取大小,然后将画布大小设置为canvas.width = bounds.width * 2和canvas.height = bounds.height * 2
标签: javascript d3.js canvas svg retina-display