【发布时间】:2022-05-06 08:32:43
【问题描述】:
我有一个只绘制大像素的画布,因为游戏完全基于框。问题是在每个图像和画布上都有图像平滑。而且非常难看。我已经浏览了互联网很长一段时间,但到目前为止,没有一个解决方案有效。
画布最终总是会模糊名称、文本和其他所有内容。图像也会模糊。
我已经尝试了我认为不是超级复杂的每个解决方案,其中涉及一堆我不理解的东西。我使用 CSS 和 JavaScript 来尝试禁用图像平滑。
这是我迄今为止尝试过的:
CSS
#gameCanvas {
image-rendering: optimizeSpeed;
image-rendering: optimizeContrast;
image-rendering: -webkit-optimize-contrast;
image-rendering: crisp-edges;
image-rendering: -moz-crisp-edges;
image-rendering: -o-crisp-edges;
image-rendering: -webkit-crisp-edges;
/* image-rendering: pixelated; */
-ms-interpolation-mode: nearest-neighbor;
}
JavaScript
game.imageSmoothingEnabled = false;
game.webkitImageSmoothingEnabled = false;
game.mozImageSmoothingEnabled = false;
game.filter = 'url(#remove-alpha)';
(其中游戏是画布的 2d 上下文) 编辑:我不确定过滤器 URL 是否有任何作用。
是否有 CSS、JavaScript 和 HTML 的组合可以禁用模糊?
game = document.getElementById('gameCanvas').getContext('2d');
document.getElementById('gameCanvas').width = window.innerWidth;
document.getElementById('gameCanvas').height = window.innerHeight;
document.getElementById('gameCanvas').addEventListener('contextmenu', e => e.preventDefault());
game.imageSmoothingEnabled = false;
game.webkitImageSmoothingEnabled = false;
game.mozImageSmoothingEnabled = false;
game.filter = 'url(#remove-alpha)';
function drawThings() {
game.font = '11px Arial';
game.fillStyle = '#000000';
game.fillText('HERES SOME TEXT', Math.random()*500, Math.random()*500);
game.fillRect(Math.random()*500, Math.random()*500, 40, 40);
}
window.onresize = function() {
game.imageSmoothingEnabled = false;
game.webkitImageSmoothingEnabled = false;
game.mozImageSmoothingEnabled = false;
game.filter = 'url(#remove-alpha)';
}
#gameCanvas {
position: absolute;
top: 80px;
left: 0px;
margin: 0px;
-webkit-user-drag: none;
user-select: none;
image-rendering: optimizeSpeed;
image-rendering: optimizeContrast;
image-rendering: -webkit-optimize-contrast;
image-rendering: crisp-edges;
image-rendering: -moz-crisp-edges;
image-rendering: -o-crisp-edges;
image-rendering: -webkit-crisp-edges;
/* image-rendering: pixelated; */
-ms-interpolation-mode: nearest-neighbor;
}
<button onclick="drawThings();">click for things</button>
<p>If you zoom in you can see that the text is blurry</p>
<canvas id="gameCanvas"></canvas>
【问题讨论】:
-
有趣的问题——您是否可以将minimal reproducible example 作为 sn-p 或在 jsFiddle 或 CodePen 等外部站点上发布?这样可以更轻松地解决您的问题
标签: javascript css html5-canvas