gello
gello

Reputation: 23

How to make scrollable canvas image in html js ?

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) 
  }
}

Upvotes: 2

Views: 4703

Answers (1)

Adelin
Adelin

Reputation: 8209

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>

Upvotes: 3

Related Questions