I need to make a table of pixels of rather big size. I used canvas, but encountered a problem: all pixels are blurry. It is not very well noticed on 100% scale, but if I make it x2 or more, it becomes very clear, that something is wrong. And finally I want it to render well on scales up to x10-x15. I have such code:
<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>
I tried to search for the solution, but nothing I found helped.
As suggested in the comments to the post, DOM image content is smoothed when up-scaled. You can change that behavior by setting the CSS rule #canvas { image-rendering: pixelated; }
So, to fix the blur behavior you have to add
#canvas { image-rendering: pixelated; }
to your CSS. Worked for me.