【问题标题】:Canvas rectangles are blurry画布矩形模糊
【发布时间】:2020-10-22 15:40:54
【问题描述】:

我需要制作一个相当大的像素表。我用canvas,但遇到一个问题:所有像素都模糊。在 100% 的规模上并没有很好地注意到它,但如果我让它成为 x2 或更多,它变得非常清楚,有些地方是错误的。最后,我希望它能够在高达 x10-x15 的范围内很好地渲染。 我有这样的代码:


        <style>
            body
            {
                background: rgb(207, 207, 207);
                overflow-x: hidden;
            }
            #main
            {
                position: absolute;
                left: 0;
                top: 0;
                height: 100%;
                width: calc(100% - 250px);
                background: lime;
            }
            canvas
            {
                width: 3180px;
                height: 800px;
                position: absolute;
                border: 2px solid black;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
            }
        </style>
    </head>
    <body id='body'>
        <div id='main'>
            <canvas id="canvas" width='3180px' height='800px'></canvas>
        </div>
        <!--<div id='menu'></div>-->
        <script>
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
            const colors = ["#FFFFFF", "#C2C2C2", "#858585", "#474747", "#000000", "#3AAFFF", "#71AAEB", "#4a76a8", "#074BF3", "#5E30EB", "#FF6C5B", "#FE2500", 
                "#FF218B", "#99244F", "#4D2C9C", "#FFCF4A", "#FEB43F", "#FE8648", "#FF5B36", "#DA5100", "#94E044", "#5CBF0D", "#C3D117", "#FCC700", "#D38301"];
            ctx.clearRect(0, 0, 3180, 800);
            for (let i = 0; i < 400; i++)
            {
                for (let j = 0; j < 1590; j++)
                {
                    ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
                    ctx.fillRect(j * 2, 2 * i, 2, 2);
                }
            }
        </script>

我试图寻找解决方案,但没有找到任何帮助。

【问题讨论】:

  • DOM 图像内容在放大时平滑。您可以通过设置 CSS 规则 #canvas { image-rendering: pixelated; } 来更改该行为
  • 哦,这很容易解决。非常感谢。我花了将近 2 个小时寻找解决方案。

标签: canvas blurry


【解决方案1】:

正如帖子中的 cmets 所建议的,DOM 图像内容在放大时会变得平滑。您可以通过设置 CSS 规则 #canvas { image-rendering: pixelated; 来更改该行为。 }

因此,要修复模糊行为,您必须在 CSS 中添加 #canvas { image-rendering: pixelated; }。为我工作。

【讨论】:

    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2016-12-03
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多