JavaScript實現(xiàn)翻轉(zhuǎn)圖片的三種方法小結(jié)
有時,我們可能需要翻轉(zhuǎn)Web應用中的媒體元素。例如,我們可能需要翻轉(zhuǎn)用于顯示相機預覽的video元素,以匹配我們實際看到的內(nèi)容,或者更正翻轉(zhuǎn)的掃描文檔的圖像。
在本文中,我們將討論使用JavaScript翻轉(zhuǎn)圖像的三種方法。
- CSS
- Canvas
- Dynamic Web TWAIN ,一個文檔掃描SDK
編寫一個HTML5頁面以調(diào)整翻轉(zhuǎn)圖像
使用以下模板創(chuàng)建一個新的HTML5頁面,然后讓我們?yōu)槠涮砑臃D(zhuǎn)圖像的功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flip an Image with JavaScript</title>
<style>
</style>
</head>
<body>
<div class="home">
<h2>Flip an Image</h2>
<button id="flipButton">Flip</button>
</div>
<script>
</script>
</body>
</html>
選擇所需方向
我們可以在兩個方向上翻轉(zhuǎn)圖像:水平和垂直??梢蕴砑右粋€select元素來選擇所需的方向。
<label>
Direction:
<select id="directionSelect">
<option>Horizontal</option>
<option>Vertical</option>
</select>
</label>
加載圖片
添加用于選擇文件的input元素,并使用按鈕觸發(fā)它。圖片將被加載到一個img元素中。
HTML:
<button id="loadFileButton">Load a File</button>
<input style="display:none;" type="file" id="file" onchange="loadImageFromFile();" accept=".jpg,.jpeg,.png,.bmp" />
<div class="imageContainer">
<img id="image"/>
</div>
<style>
.imageContainer {
overflow: auto;
}
#image {
max-width: 50%;
}
</style>
JavaScript:
function loadImageFromFile(){
let fileInput = document.getElementById("file");
let files = fileInput.files;
if (files.length == 0) {
return;
}
let file = files[0];
fileReader = new FileReader();
fileReader.onload = function(e){
document.getElementById("image").src = e.target.result;
};
fileReader.onerror = function () {
console.warn('oops, something went wrong.');
};
fileReader.readAsDataURL(file);
}
使用CSS翻轉(zhuǎn)圖像
我們可以使用CSS屬性transform來翻轉(zhuǎn)HTML元素,用法如下:
img.style.transform = "scaleY(-1)"; //flip vertically img.style.transform = "scaleX(-1)"; //flip horizontally img.style.transform = "scaleX(-1) scaleY(-1)"; //flip both vertically and horizontally
下面是在頁面中寫的用于翻轉(zhuǎn)圖像的代碼,它會記住之前的翻轉(zhuǎn)狀態(tài)。
function flipImageWithCSS(){
let img = document.getElementById("image");
if (document.getElementById("directionSelect").selectedIndex == 0) {
if (img.style.transform.indexOf("scaleX") != -1) {
img.style.transform = img.style.transform.replace("scaleX(-1)","");
}else{
img.style.transform = img.style.transform+" scaleX(-1)";
}
}else{
if (img.style.transform.indexOf("scaleY") != -1) {
img.style.transform = img.style.transform.replace("scaleY(-1)","");
}else{
img.style.transform = img.style.transform+" scaleY(-1)";
}
}
}
使用Canvas翻轉(zhuǎn)圖像
HTML5提供了一個canvas標簽,我們可以用它操作圖像數(shù)據(jù)。與只改變視覺效果的CSS不同,我們可以使用它來實際獲得翻轉(zhuǎn)的圖像。
向頁面添加一個隱藏的canvas元素。
<canvas id="canvasHidden"></canvas>
<style>
#canvasHidden {
display: none;
}
</style>
添加一個select元素以選擇要使用的翻轉(zhuǎn)方法。
<label>
Method:
<select id="methodSelect">
<option>CSS</option>
<option>Canvas</option>
</select>
</label>
當所選方法為"Canvas"時,使用canvas翻轉(zhuǎn)圖像。
let method = document.getElementById("methodSelect").selectedIndex;
if (method == 0) {
flipImageWithCSS();
}else if (method == 1){
document.getElementById("image").style.transform = "";
flipImageWithCanvas();
}
使用Canvas翻轉(zhuǎn)圖像的具體步驟:
將canvas的大小設置為圖像的大小。
const image = document.getElementById("image");
const canvas = document.getElementById("canvasHidden");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
獲取canvas的context以執(zhí)行操作。
const ctx = canvas.getContext("2d");
將原點(0,0)設置為(width,0),然后在水平方向上使用縮放系數(shù)-1處理圖像以水平翻轉(zhuǎn)圖像。我們可以使用類似的邏輯來垂直翻轉(zhuǎn)圖像。
if (document.getElementById("directionSelect").selectedIndex == 0) {
context.translate(width, 0);
context.scale(-1, 1);
}else{
context.translate(0, height);
context.scale(1, -1);
}
使用drawImage繪制圖像內(nèi)容。
context.drawImage(image, 0, 0);
顯示翻轉(zhuǎn)后的圖像。
image.src = canvas.toDataURL();
使用Dynamic Web TWAIN翻轉(zhuǎn)圖像
Dynamic Web TWAIN是一個文檔掃描SDK,可以在瀏覽器中掃描文檔。它提供了各種圖像處理方法。我們可以使用其Flip和Mirror方法翻轉(zhuǎn)圖像。
使用它的優(yōu)點是,它可以用于批量處理大量圖像,因為處理是使用本地進程完成的。
以下是使用它的步驟:
在頁面中引入Dynamic Web TWAIN。
<script src="https://unpkg.com/dwt@18.4.2/dist/dynamsoft.webtwain.min.js"></script>
初始化一個Web TWAIN的實例并使用它來翻轉(zhuǎn)圖像??梢栽?a target="_blank">此處申請其許可證。
let DWObject;
Dynamsoft.DWT.AutoLoad = false;
Dynamsoft.DWT.ProductKey = "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ=="; //one-day trial
Dynamsoft.DWT.ResourcesPath = "https://unpkg.com/dwt@18.4.2/dist";
async function flipImageWithWebTWAIN(){
if (!DWObject) {
await initDWT();
}
DWObject.RemoveAllImages();
let response = await fetch(document.getElementById("image").src);
let buffer = await response.arrayBuffer();
DWObject.LoadImageFromBinary(buffer,
function(){
if (document.getElementById("directionSelect").selectedIndex == 0) {
DWObject.Mirror(0,
function(){ //success
document.getElementById("image").src = DWObject.GetImageURL(0);
},
function(errorCode, errorString){ //fail
console.log(errorString);
});
}else{
DWObject.Flip(0,
function(){ //success
document.getElementById("image").src = DWObject.GetImageURL(0);
},
function(errorCode, errorString){ //fail
console.log(errorString);
});
}
},
function(errorCode, errorString){
console.log(errorString);
})
}
function initDWT(){
return new Promise((resolve, reject) => {
const title = document.querySelector("h2").innerText;
document.querySelector("h2").innerText = "Loading Dynamic Web TWAIN...";
Dynamsoft.DWT.CreateDWTObjectEx(
{
WebTwainId: 'dwtcontrol'
},
function(obj) {
DWObject = obj;
document.querySelector("h2").innerText = title;
resolve();
},
function(err) {
console.log(err);
document.querySelector("h2").innerText = "Failed to load Dynamic Web TWAIN";
reject(err);
}
);
})
}
源代碼
可以在以下倉庫中找到所有代碼和在線演示:
github.com/tony-xlh/Flip-Image-JavaScript
以上就是JavaScript實現(xiàn)翻轉(zhuǎn)圖片的三種方法小結(jié)的詳細內(nèi)容,更多關于JavaScript翻轉(zhuǎn)圖片的資料請關注腳本之家其它相關文章!
相關文章
JS實現(xiàn)網(wǎng)頁標題隨機顯示名人名言的方法

