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 图像到 CanvasrenderTiffImage(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) {// 图片更宽,宽度填满 canvasdrawWidth = canvasWidth * dpr;drawHeight = drawWidth / imgRatio;} else {// 图片更高,高度填满 canvasdrawHeight = 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); // 清空 canvasctx.drawImage(image, offsetX, offsetY, drawWidth, drawHeight);};xhr.send(); // 发送请求},}
}