通过单击浏览器菜单的 Print 选项或按快捷键 Ctrl+P(或 macOS 上的 command+P),可以打印网页。调用 window.print() 方法将提供打印整个页面的相同结果。

为了打印图像,我们可以将 img 元素插入到伪 iframe 元素中,并在 iframe 的窗口上调用 print() 方法。

假设页面具有图像元素和打印按钮,结构如下所示:

<img id="image" src="https://images.pexels.com/photos/753626/pexels-photo-753626.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
<button class="print-btn" id="print">
  打印
</button>

可以在按钮的单击事件中处理打印图像:

const printBtn = document.getElementById('print')

printBtn.addEventListener('click', function() {
    // ...
})

创建一个假 iframe

// 创建一个假 iframe
const iframe = document.createElement('iframe')

// 隐藏它
iframe.style.height = 0
iframe.style.visibility = 'hidden'
iframe.style.width = 0

// 设置 iframe 的源
iframe.setAttribute('srcdoc', '<html><body></body></html>')

document.body.appendChild(iframe)

尽管 iframe 源是一个简单的 HTML,而不是 src 属性定义的远程路径,但我们必须等待 iframe 完全加载:

iframe.addEventListener('load', function () {
    // 克隆图像
    const image = document.getElementById('image').cloneNode()
    image.style.maxWidth = '100%'

    // 将图像附加到 iframe 的 body 上
    const body = iframe.contentDocument.body
    body.style.textAlign = 'center'
    body.appendChild(image)
})

加载图像后,立即在 iframe 的窗口上调用 print() 方法:

iframe.addEventListener('load', function() {
    // ...
    image.addEventListener('load', function() {
        // 当图像准备就绪时调用打印
        iframe.contentWindow.print()
    })
})

查看效果