使用JavaScript平移和縮放圖像的示例代碼
前言
平移和縮放是查看圖像時常用的功能。我們可以放大圖像以查看更多細(xì)節(jié),進(jìn)行圖像編輯。
Dynamsoft Document Viewer是一個用于此目的的SDK,它為文檔圖像提供了一組查看器。在本文中,我們將演示如何使用它來平移和縮放圖像。此外,我們還將探討如何使用JavaScript從頭實現(xiàn)這一功能。
使用Dynamsoft Document Viewer平移和縮放圖像
創(chuàng)建一個包含以下模板的新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>
在頁面中包含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">這里申請一個證書。
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)建一個新的文檔實例。
const docManager = Dynamsoft.DDV.documentManager; const doc = docManager.createDocument();
創(chuàng)建一個Edit Viewer實例,將其綁定到一個容器,然后用它來查看我們剛剛創(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選擇圖像文件并將其加載到文檔實例中,然后可以用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)滾輪放大、縮小和平移圖像。在移動設(shè)備上,我們可以通過雙指實現(xiàn)縮放。
從頭開始實現(xiàn)平移和縮放
有幾種方法可以實現(xiàn)平移和縮放。
- 使用絕對像素值。它易于理解,可以有滾動條。
- 使用CSS transform。它可以使用GPU來獲得更好的性能,但不能保留滾動條。
- 使用Canvas。它具有較高的性能和定制性。Dynamsoft Document Viewer使用此方法。
下面,我們將使用第一種方式進(jìn)行演示。
創(chuàng)建一個容器作為查看器。包含一張圖像。
<div id="viewer"> <img id="image"/> </div>
樣式:
使用flex布局來對齊組件。
查看器的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);
})
}
添加一個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)或觸摸屏實現(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事件以支持縮放。計算兩個觸摸點的距離,以知道需要放大還是縮小。
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實現(xiàn)了平移和縮放功能。
以上就是使用JavaScript平移和縮放圖像的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于JavaScript平移和縮放圖像的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
javascript 根據(jù)歌名獲取播放地址和歌詞內(nèi)容
在前幾天做在線聽歌的過程中,碰到了根據(jù)歌名獲取播放地址和LRC文件內(nèi)容的問題,今晚花了幾個小時把接口整理了一下2009-06-06
Js使用WScript.Shell對象執(zhí)行.bat文件和cmd命令
這篇文章主要介紹了Js使用WScript.Shell對象執(zhí)行.bat文件和cmd命令,需要的朋友可以參考下2014-12-12
Sublime?Text?3插件Minify的安裝與使用(js代碼壓縮)
這篇文章主要介紹了Sublime?Text?3插件Minify的安裝與使用(js代碼壓縮),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01
javascript代碼調(diào)試之console.log 用法圖文詳解
對于開始學(xué)js的朋友可能不知道為什么用console.log,頁面中也看不到信息,對于這個console.log腳本之家小編特整理與介紹一下,方便需要的朋友2016-09-09
javascript實現(xiàn)動態(tài)CSS換膚技術(shù)的腳本
javascript實現(xiàn)動態(tài)CSS換膚技術(shù)的腳本...2007-06-06
js prototype 格式化數(shù)字 By shawl.qiu
js prototype 格式化數(shù)字 By shawl.qiu...2007-04-04
JS操作XML實例總結(jié)(加載與解析XML文件、字符串)
這篇文章主要介紹了JS操作XML的方法,結(jié)合實例形式總結(jié)分析了JavaScript加載與解析XML文件及字符串的相關(guān)技巧,需要的朋友可以參考下2015-12-12

