我有一块小画布:
<canvas id="game-canvas" width="256" height="232"></canvas>
我正在缩放它以适应窗口:
html,
body {
padding: 0;
margin: 0;
overflow: hidden;
image-rendering: pixelated;
background: black;
}
canvas {
background: black;
width: 100vh;
margin: auto;
display: block;
}
这就是我使用外部字体在画布上绘制文本的方式。
const canvas = document.querySelector('#game-canvas');
const ctx = canvas.getContext('2d');
---
const draw = () =>
{
// draw objects in mounted scene
mainScene.draw(ctx, 0, 0);
var numRupees = 0;
var numKeys = 0;
var numBombs = 0;
// text
ctx.fillText('X' + numRupees, gridCells(13), gridCells(2.75));
ctx.fillText('X' + numKeys, gridCells(13), gridCells(4.75));
ctx.fillText('X' + numBombs, gridCells(13), gridCells(5.75));
ctx.fillText("It's dangerous to go", canvas.width / 2, canvas.height / 2 - 15);
ctx.fillText("alone! Take this.", canvas.width / 2, canvas.height / 2 - 7.5);
};
---
const tlozFont = new FontFace('tloz', 'url(./public/fonts/the-legend-of-zelda-nes.ttf)');
tlozFont.load().then(function (font) {
document.fonts.add(font);
document.body.classList.add('fonts-loaded');
console.log('Font loaded.');
ctx.font = '8px tloz';
ctx.textAlign = 'center';
ctx.fillStyle = 'white';
});
问题是我的画布渲染清晰,但文本像素化 - 因为我必须使用 8px 的字体大小来正确调整其大小。我注意到,当我将字体大小设置为 1000px 之类的疯狂值时,它很清晰 - 但显然太大而无法适应画布。
我的画布:
是否可以以更大的尺寸渲染字体,然后将其缩小以适合画布?
我花了几天时间尝试在谷歌上找到的每一个解决方案,但没有任何效果。它们要么使画布和字体太小,要么使字体清晰但画布模糊。
你可以,但不值得。如果将大字体缩小以占据与 8px 字体大小文本直接写入较小画布时所占据的画布像素相同的画布像素,则无法期望改善外观。画布元素是像素化。
您可能需要查看 https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering 使用不同的方法放大画布,或者使用更大的画布开始和缩小-缩放它以适应较小的视口。