首页 > 解决方案 > 如何在 html js 中制作可滚动的画布图像?

问题描述

我正在尝试使用画布图像制作网页。画布图像应该是可滚动的(x,y)。但是我的代码只做垂直滚动而不是水平滚动。

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

标签: javascripthtml

解决方案


如指定here,您可以按如下方式实现:

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>


推荐阅读