<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>使用fabric.js裁剪和显示图片</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.5.0/fabric.min.js"></script>
</head>
<body>
<canvas id="canvas" ></canvas>
<img id="sourceImage" src="YOUR URL" style="display: none;">
<script>
// var canvas = new fabric.Canvas('canvas');
var canvas = new fabric.StaticCanvas("canvas");
var sourceImage = document.getElementById('sourceImage');
//截图位置
const cropXywh = [821,3799,97,90]
fabric.Image.fromURL(sourceImage.src, function(img) {
canvas.add(img);
var text = new fabric.Text('这里是文本描述', {
left: 0,
top: 0,
fontSize: 16,
fill: 'red'
});
var textWidth = text.width; // 获取文本的宽度
var textHeight = text.height; // 获取文本的高度
img.set({
left: 0,
top: textHeight,
width: cropXywh[2],
height: cropXywh[3],
cropX: cropXywh[0], // 裁剪区域左上角x坐标
cropY: cropXywh[1], // 裁剪区域左上角y坐标
cropWidth: cropXywh[2], // 裁剪区域宽度
cropHeight: cropXywh[3] // 裁剪区域高度
});
let widths = [cropXywh[2],textWidth];
let maxWidth = Math.max(...widths);
let maxHeight = cropXywh[3]+textHeight;
canvas.setWidth(maxWidth);
canvas.setHeight(maxHeight);
canvas.add(text);
canvas.renderAll(); // 更新Canvas
//若使用elementui可以显示局部图放大效果
//let imgData = canvas.toDataURL({ format: "png", quality: 0.8 });
// imageData.value = [imgData]
// showImageViewer.value = true
});
</script>
</body>
</html>
效果图:
再结合el-image-viewer可以实现大图预览局部图的效果。文章来源:https://www.toymoban.com/news/detail-835104.html
文章来源地址https://www.toymoban.com/news/detail-835104.html
// 图片预览
<el-image-viewer
style="z-index:1500"
v-if="showImageViewer"
@close="()=>{showImageViewer = false}"
:url-list="imageData"
>
onMounted(() => {
// 通过遮罩层关闭图片预览
document.addEventListener('click',function(e){
if(e.target.className=="el-image-viewer__mask"){
let close = document.querySelector(".el-image-viewer__close");
if(close){
close.click();
showImageViewer.value = false
}else{
close = document.querySelector(".el-icon-circle-close");
if(close){
close.click();
showImageViewer.value = false
}
}
}
});
});
到了这里,关于【Vue】fabricjs 实现局部截图及el-image-viewer大图预览的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!