简体   繁体   中英

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM