使用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。可以在這里申請一個證書。
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)文章
將\u8BF7\u9009\u62E9 這樣的字符串轉(zhuǎn)為漢字的代碼
如何把 \u8BF7\u9009\u62E9 這樣的字符串轉(zhuǎn)為漢字,喜歡的朋友可以參考下。2010-11-11
JavaScript Window瀏覽器對象模型方法與屬性匯總
本文給大家匯總分享的是JavaScript Window瀏覽器對象模型方法與屬性,十分的細(xì)致全面,這里推薦給大家,有需要的小伙伴可以參考下。2015-04-04

