欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用JavaScript平移和縮放圖像的示例代碼

 更新時(shí)間:2024年08月14日 10:55:43   作者:xulihang  
平移和縮放是查看圖像時(shí)常用的功能,我們可以放大圖像以查看更多細(xì)節(jié),進(jìn)行圖像編輯,Dynamsoft Document Viewer是一個(gè)用于此目的的SDK,它為文檔圖像提供了一組查看器,在本文中,我們將演示如何使用它來(lái)平移和縮放圖像,需要的朋友可以參考下

前言

平移和縮放是查看圖像時(shí)常用的功能。我們可以放大圖像以查看更多細(xì)節(jié),進(jìn)行圖像編輯。

Dynamsoft Document Viewer是一個(gè)用于此目的的SDK,它為文檔圖像提供了一組查看器。在本文中,我們將演示如何使用它來(lái)平移和縮放圖像。此外,我們還將探討如何使用JavaScript從頭實(shí)現(xiàn)這一功能。

使用Dynamsoft Document Viewer平移和縮放圖像

創(chuàng)建一個(gè)包含以下模板的新HTML文件。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Edit Viewer</title>
  <style>
  </style>
</head>
<body>
</body>
<script>
</script>
</html>

在頁(yè)面中包含Dynamsoft Document Viewer的文件。

<script src="https://cdn.jsdelivr.net/npm/dynamsoft-document-viewer@1.1.0/dist/ddv.js"></script>
<link rel="stylesheet"  rel="external nofollow" >

使用許可證初始化Dynamsoft Document Viewer??梢栽?a rel="external nofollow" target="_blank">這里申請(qǐng)一個(gè)證書(shū)。

Dynamsoft.DDV.Core.license = "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ=="; //one-day trial
Dynamsoft.DDV.Core.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-document-viewer@1.1.0/dist/engine";// Lead to a folder containing the distributed WASM files
await Dynamsoft.DDV.Core.init();

創(chuàng)建一個(gè)新的文檔實(shí)例。

const docManager = Dynamsoft.DDV.documentManager;
const doc = docManager.createDocument();

創(chuàng)建一個(gè)Edit Viewer實(shí)例,將其綁定到一個(gè)容器,然后用它來(lái)查看我們剛剛創(chuàng)建的文檔。

HTML:

<div id="viewer"></div>

JavaScript:

const uiConfig = {
  type: Dynamsoft.DDV.Elements.Layout,
  flexDirection: "column",
  className: "ddv-edit-viewer-mobile",
  children: [
    Dynamsoft.DDV.Elements.MainView // the view which is used to display the pages
  ],
};
editViewer = new Dynamsoft.DDV.EditViewer({
  uiConfig: uiConfig,
  container: document.getElementById("viewer")
});

editViewer.openDocument(doc.uid);

CSS:

#viewer {
  width: 320px;
  height: 480px;
}

使用input選擇圖像文件并將其加載到文檔實(shí)例中,然后可以用Edit Viewer進(jìn)行查看。

HTML:

<label>
  Select an image:
  <br/>
  <input type="file" id="files" name="files" onchange="filesSelected()"/>
</label>

JavaScript:

async function filesSelected(){
  let filesInput = document.getElementById("files");
  let files = filesInput.files;
  if (files.length>0) {
    const file = files[0];
    const blob = await readFileAsBlob(file);
    await doc.loadSource(blob); // load image
  }
}

function readFileAsBlob(file){
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = async function(e){
      const response = await fetch(e.target.result);
      const blob = await response.blob();
      resolve(blob);
    };
    fileReader.onerror = function () {
      reject('oops, something went wrong.');
    };
    fileReader.readAsDataURL(file);
  })
}

然后,我們可以按住控制鍵,使用鼠標(biāo)滾輪放大、縮小和平移圖像。在移動(dòng)設(shè)備上,我們可以通過(guò)雙指實(shí)現(xiàn)縮放。

從頭開(kāi)始實(shí)現(xiàn)平移和縮放

有幾種方法可以實(shí)現(xiàn)平移和縮放。

  • 使用絕對(duì)像素值。它易于理解,可以有滾動(dòng)條。
  • 使用CSS transform。它可以使用GPU來(lái)獲得更好的性能,但不能保留滾動(dòng)條。
  • 使用Canvas。它具有較高的性能和定制性。Dynamsoft Document Viewer使用此方法。

下面,我們將使用第一種方式進(jìn)行演示。

  • 創(chuàng)建一個(gè)容器作為查看器。包含一張圖像。

<div id="viewer">
  <img id="image"/>
</div>

樣式:

使用flex布局來(lái)對(duì)齊組件。

查看器的CSS:

#viewer {
  width: 320px;
  height: 480px;
  padding: 10px;
  border: 1px solid black;
  overflow: auto;
  display: flex;
  align-items: center;
}

加載所選圖像文件。使圖像的寬度適合查看器。

let currentPercent;
async function filesSelected(){
  let filesInput = document.getElementById("files");
  let files = filesInput.files;
  if (files.length>0) {
    const file = files[0];
    const blob = await readFileAsBlob(file);
    const url = URL.createObjectURL(blob);
    loadImage(url);
  }
}

function loadImage(url){
  let img = document.getElementById("image");
  img.src = url;
  img.onload = function(){
    let viewer = document.getElementById("viewer");
    let percent = 1.0;
    resizeImage(percent);
  }
}

function resizeImage(percent){
  currentPercent = percent;
  let img = document.getElementById("image");
  let viewer = document.getElementById("viewer");
  let borderWidth = 1;
  let padding = 10;
  let ratio = img.naturalWidth/img.naturalHeight;
  let newWidth = (viewer.offsetWidth - borderWidth*2 - padding*2) * percent
  img.style.width = newWidth + "px";
  img.style.height = newWidth/ratio + "px";
}

function readFileAsBlob(file){
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = async function(e){
      const response = await fetch(e.target.result);
      const blob = await response.blob();
      resolve(blob);
    };
    fileReader.onerror = function () {
      reject('oops, something went wrong.');
    };
    fileReader.readAsDataURL(file);
  })
}

添加一個(gè)wheel事件,以便在按下控制鍵的情況下使用鼠標(biāo)進(jìn)行縮放。

img.addEventListener("wheel",function(e){
  if (e.ctrlKey || e.metaKey) {
    if (e.deltaY < 0) {
      zoom(true);
    }else{
      zoom(false);
    }
    e.preventDefault();
  }
});

function zoom(zoomin,percentOffset){
  let offset = percentOffset ?? 0.1;
  if (zoomin) {
    currentPercent = currentPercent + offset;
  }else{
    currentPercent = currentPercent - offset;
  }
  currentPercent = Math.max(0.1,currentPercent);
  resizeImage(currentPercent);
}

添加pointer事件以使用鼠標(biāo)或觸摸屏實(shí)現(xiàn)平移。

let downPoint;
let downScrollPosition;
img.addEventListener("pointerdown",function(e){
  previousDistance = undefined;
  downPoint = {x:e.clientX,y:e.clientY};
  downScrollPosition = {x:viewer.scrollLeft,y:viewer.scrollTop}
});
img.addEventListener("pointerup",function(e){
  downPoint = undefined;
});
img.addEventListener("pointermove",function(e){
  if (downPoint) {
    let offsetX = e.clientX - downPoint.x;
    let offsetY = e.clientY - downPoint.y;
    let newScrollLeft = downScrollPosition.x - offsetX;
    let newScrollTop = downScrollPosition.y - offsetY;
    viewer.scrollLeft = newScrollLeft;
    viewer.scrollTop = newScrollTop;
  }
});

添加touchmove事件以支持縮放。計(jì)算兩個(gè)觸摸點(diǎn)的距離,以知道需要放大還是縮小。

img.addEventListener("touchmove",function(e){
  if (e.touches.length === 2) {
    const distance = getDistanceBetweenTwoTouches(e.touches[0],e.touches[1]);
    if (previousDistance) {
      if ((distance - previousDistance)>0) { //zoom
        zoom(true,0.02);
      }else{
        zoom(false,0.02);
      }
      previousDistance = distance;
    }else{
      previousDistance = distance;
    }
  }
  e.preventDefault();
});

function getDistanceBetweenTwoTouches(touch1,touch2){
  const offsetX = touch1.clientX - touch2.clientX;
  const offsetY = touch1.clientY - touch2.clientY;
  const distance = offsetX * offsetX + offsetY + offsetY;
  return distance;
}

好了,我們已經(jīng)用JavaScript實(shí)現(xiàn)了平移和縮放功能。

以上就是使用JavaScript平移和縮放圖像的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于JavaScript平移和縮放圖像的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論