主要参考了插件 AttachFlow 和 obsidian-highlighter,谢谢你们~
平时只有少量查看大图需求,就写了一个简单的。
main.js:
const ob = require('obsidian')
, import_mouse = (ob)=> new class {
restLength = (mouse, screen)=> mouse < screen / 2 ? screen - mouse : mouse
keyMoveImg = (evt)=> {
const isKey = evt.altKey
, { target, view } = evt, targetNotImg = target.tagName != 'IMG'
if (targetNotImg && this.hoverOn) this.hoverOn = !1
if (!isKey || targetNotImg || !view || this.hoverOn) return
const pop = new ob.HoverPopover(view, target, 200), { hoverEl } = pop
const { naturalWidth, naturalHeight } = target
, ratio = naturalHeight / naturalWidth
, restWidth = this.restLength(evt.clientX, view.innerWidth)
, expectHeight = restWidth * ratio
, restHeight = this.restLength(evt.clientY, view.innerHeight)
, expectWidth = restHeight / ratio
let calcByWidth
if (expectWidth < restWidth && expectHeight < restHeight)
calcByWidth = restWidth * expectHeight > restHeight * expectWidth;
else calcByWidth = expectWidth > restWidth
let width = calcByWidth ? restWidth : expectWidth
width = Math.min(800, width)
Object.assign(hoverEl.style, {
width: `${width}px`, height: `${width * ratio}px`,
'background-image': `url(${target.src})`, 'background-size': 'cover',
})
hoverEl.onwheel = e=> {
const scale = e.deltaY > 0 ? 0.8 : 1.2 // 20% 缩放
, mouseX = e.clientX, mouseY = e.clientY, width = hoverEl.offsetWidth * scale
Object.assign(hoverEl.style, {
width: `${width}px`, height: `${width * ratio}px`,
left: `${mouseX - (mouseX - hoverEl.offsetLeft) * scale}px`,
top: `${mouseY - (mouseY - hoverEl.offsetTop) * scale}px`,
})
}
this.hoverOn = !0; pop.onunload = ()=> this.hoverOn = !1
}
}
module.exports = class extends ob.Plugin {
onload() {
let Timer; const { keyMoveImg } = import_mouse(ob)
this.registerEvent(
this.app.workspace.on('active-leaf-change', (leaf)=> {
if (Timer) clearTimeout(Timer)
Timer = setTimeout(()=> {
const { view } = leaf; if (!view) return
this.registerDomEvent(view.contentEl, 'mousemove', keyMoveImg)
})
}),
)
}
onunload() {}
}
keyMoveImg()
第 1 行isKey
控制按住什么键悬停触发大图,这里设置的是 Alt 键。鼠标移动到大图区域后不用再按住键。- 鼠标滚轮放大缩小。