Reputation: 21
I am using a device that has devicePixelRatio
of 1
. On scroll, I am re-rendering the canvas by adding 1
or -1
to the y
position. It affects the rendering quality and more importantly, the rendering position keeps changing on scroll. For instance, if I render with 2px space which is in between the line and the text it differs on scroll. This reproduces only when you scroll very slightly.
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
let width = 500;
let height = 500;
canvas.width = width * devicePixelRatio;
canvas.height = height * devicePixelRatio;
ctx.scale(devicePixelRatio,devicePixelRatio)
let startY = 0;
let lineHeight = 30;
let offSet = 0.5;
let padding = 2;
function draw(){
for(let i=0;i<30;i++){
let y = (i*lineHeight)+(startY%lineHeight);
ctx.beginPath()
ctx.moveTo(250+offSet,y+offSet);
ctx.lineTo(250+100+offSet,y+offSet);
ctx.stroke();
ctx.font = '20px Arial';
ctx.fillText('text',250+30+offSet,y+offSet-padding);
}
}
draw();
canvas.addEventListener('wheel',()=>{
let wheel = Math.round(event.wheelDeltaY/6);
ctx.clearRect(0,0,500,500);
startY += wheel;
draw();
});
canvas{
width : 500px;
height : 500px;
border : 1px solid;
}
<canvas></canvas>
How can I fix this?
You can see my project on codepen too.
Upvotes: 2
Views: 119