0

I want to add a drawing canvas on top of a website that stretches for the whole height of a website.

I specified canvas.height = window.innerHeight; canvas.width = window.innerWidth; and it seems to work for the viewport, but when I scroll, I cannot draw bellow it.

I assume I need to update the canvas.height every time I scroll down, but I cannot seem to find a solution.

Here is the code:

window.addEventListener ("load", () => {
  const canvas = document.querySelector ("#canvas");
  const ctx = canvas.getContext ("2d");

//Resizing

canvas.height = window.innerHeight;
canvas.width = window.innerWidth;

//Variables

let painting = false;

function startPosition (e){
  painting = true;
  draw (e);
}
function finishedPosition (){
  painting = false;
  ctx.beginPath();
}


function draw (e){
  if (!painting) return;
  ctx.lineWidth = 1;
  ctx.lineCap = "round";

  ctx.lineTo(e.clientX, e.clientY);
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(e.clientX, e.clientY);
}


//Event listeners

canvas.addEventListener ("mousedown", startPosition);
canvas.addEventListener ("mouseup", finishedPosition);
canvas.addEventListener ("mousemove", draw);


});

I would appreciate any help on this!

1 Answer 1

1

This appears to be due to the use of window.innerHeight. Try using document.querySelector('body').clientHeight as that should give you the height of the entire body of the page.

Also, use MouseEvent.pageX and .pageY because .clientY will not update when the user scrolls the page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.