npm install html2canvas
<template>
<div ref="contentToCapture" class="scrollable-content">
<!-- Your scrollable content here -->
<div v-for="item in items" :key="item.id" class="item">
{{ item.content }}
</div>
</div>
<button @click="captureAndDownload">Download as Image</button>
</template>
<script>
import html2canvas from 'html2canvas';
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
{ id: 3, content: 'Item 3' },
// Add more items as needed
]
};
},
methods: {
async captureAndDownload() {
const element = this.$refs.contentToCapture;
// Ensure the element is fully visible and not clipped
element.style.height = 'auto';
element.style.overflow = 'visible';
const canvas = await html2canvas(element, {
useCORS: true,
scale: 2, // Increase the scale for better quality
windowWidth: document.documentElement.scrollWidth,
windowHeight: document.documentElement.scrollHeight,
});
const image = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = image;
link.download = 'captured-content.png';
link.click();
// Restore the original styles
element.style.height = '';
element.style.overflow = '';
}
}
};
</script>
<style>
.scrollable-content {
width: 100%;
max-height: 400px;
overflow-y: scroll;
border: 1px solid #ccc;
}
.item {
padding: 10px;
border-bottom: 1px solid #ddd;
}
</style>
我的代码参考了上图
实际代码如下图所示:
