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) 
  }
}
gello
  • 23
  • 1
  • 4

1 Answers1

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>
Adelin
  • 7,809
  • 5
  • 37
  • 65
  • Thanks. Do you know how to make the image move on with mouse ? like we do in google map. – gello Jul 12 '18 at 06:07
  • You can find inspiration on this answer: https://stackoverflow.com/questions/15036386/make-image-drawn-on-canvas-draggable-with-javascript – Adelin Jul 12 '18 at 06:19