1、安装 tiff
cnpm install tiff.js
2、main.js 引入
import Tiff from 'tiff.js';
<template>
<canvas id="tiff-canvas" style="width: 200px; height: auto;"></canvas>
</template>
<script>
export default {
mounted(){
this.renderTiffImage('aaa.tif', 'tiff-canvas');
}
methods:{
// 渲染 TIFF 图像到 Canvas
renderTiffImage(tiffUrl, canvasId) {
// 获取 Canvas 元素
const canvas = document.getElementById(canvasId);
if (!canvas) return;
// 获取 Canvas 的显示尺寸
const canvasWidth = 1400; // Canvas 显示的宽度
const canvasHeight = 1000; // Canvas 显示的高度
// 计算设备的像素比率
const dpr = window.devicePixelRatio || 1;
// 设置 Canvas 的物理大小
canvas.width = canvasWidth * dpr;
canvas.height = canvasHeight * dpr;
// 创建一个 XMLHttpRequest 请求来加载 TIFF 文件
const xhr = new XMLHttpRequest();
xhr.open('GET', tiffUrl, true);
xhr.responseType = 'arraybuffer'; // 设置响应类型为二进制
// 当请求成功时,使用 tiff.js 解析 TIFF 文件
xhr.onload = () => {
const arrayBuffer = xhr.response;
const tiff = new Tiff({ buffer: arrayBuffer }); // 使用 tiff.js 解析 TIFF 文件
const image = tiff.toCanvas(); // 获取 Canvas 对象
// 获取 TIFF 图像的原始尺寸
const imgWidth = image.width;
const imgHeight = image.height;
// 计算等比例缩放的宽高
let drawWidth, drawHeight;
const imgRatio = imgWidth / imgHeight;
const canvasRatio = canvasWidth / canvasHeight;
if (imgRatio > canvasRatio) {
// 图片更宽,宽度填满 canvas
drawWidth = canvasWidth * dpr;
drawHeight = drawWidth / imgRatio;
} else {
// 图片更高,高度填满 canvas
drawHeight = canvasHeight * dpr;
drawWidth = drawHeight * imgRatio;
}
// 计算图片绘制的起始位置(居中显示)
const offsetX = (canvas.width - drawWidth) / 2;
const offsetY = (canvas.height - drawHeight) / 2;
// 获取 Canvas 的上下文,并将图像绘制到 Canvas 上
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空 canvas
ctx.drawImage(image, offsetX, offsetY, drawWidth, drawHeight);
};
xhr.send(); // 发送请求
},
}
}