2

I'm trying to make a web page with canvas image. Canvas image should be scrollable (x, y). But my code does vertical scroll only not the horizontal.

html

<nav>
<main>
  <canvas id="floornet"></canvas>
</main>

js

window.onload = function() {

  // Get the image
  const image = new Image()
  image.src = 'https://upload.wikimedia.org/wikipedia/commons/3/36/Hopetoun_falls.jpg'

  // Wait Till the Image is loaded
  image.onload = function() {
    drawCanvas(image)
  }

  function drawCanvas(image) {
    // Create canvas context
    const canvas = document.getElementById('floornet')
    const context = canvas.getContext("2d")

    canvas.width = image.height
    canvas.height = image.height

    // Draw image to the canvas
    context.drawImage(image, 0, 0) 
  }
}

1 Answer 1

3

As specified here, you can achieve that as follows:

window.onload = function() {

  // Get the image
  const image = new Image()
  image.src = 'https://upload.wikimedia.org/wikipedia/commons/3/36/Hopetoun_falls.jpg'

  // Wait Till the Image is loaded
  image.onload = function() {
    drawCanvas(image)
  }

  function drawCanvas(image) {
    // Create canvas context
    const canvas = document.getElementById('floornet')
    const context = canvas.getContext("2d")

    canvas.width = image.height 
    canvas.height = image.height 

    // Draw image to the canvas
    context.drawImage(image, 0, 0) 
  }
}
<main>
<div style="max-height: 256px;max-width:256px;overflow: scroll;">
          <canvas width="512px" height="512px" id="floornet"></canvas>
</div>  
</main>

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

2 Comments

Thanks. Do you know how to make the image move on with mouse ? like we do in google map.
You can find inspiration on this answer: stackoverflow.com/questions/15036386/…

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.