2

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.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • If it is reproducible, then you should be able to replace the `wheel` handler with something more reliable so we don't have to find the right amount of movement for a _"very slightly"_ scroll. – Andreas Aug 18 '22 at 07:26
  • Is your canvas in a scrollable box somehow? What browser + OS do you experience this with? – Kaiido Aug 18 '22 at 08:31
  • @Kaiido, I have only one element in HTML tab that is canvas and it doesn't overflow its width.I was using chrome latest version. OS-windows. Machine devicePixelRation-1. Browser zoom - below 100%(ex.90%,80%) – UNKNOWN .MR. Aug 18 '22 at 08:48
  • 1
    Have a look in your Control Panels > Display > Scale and Layout. Make sure it's set to 100%. – Kaiido Aug 18 '22 at 08:55
  • @Kaiido, I am a developer, I can't say this to every user of mine. – UNKNOWN .MR. Aug 19 '22 at 06:35
  • Of course, but the first step to find a cure is to understand the disease. – Kaiido Aug 19 '22 at 06:46
  • @Kaiido, Control Panels > Display > Scale set to 100%.but, still that issue comes. – UNKNOWN .MR. Aug 22 '22 at 16:31

0 Answers0