In this article, we will learn how to use html2canvas in vue.js
Step 1: Create a new vue project:
vue create vue-html2canvas-demo
Step 2: Install require packages:
npm i html2canvas
Step 3: Open App.vue file and add the following in it:
<template> <div id="printTemplate"> <img alt="Vue logo" src="./assets/logo.png" /> <HelloWorld msg="Welcome to Your Vue.js App" /> </div> </template> <script> import html2canvas from "html2canvas"; import HelloWorld from "./components/HelloWorld.vue"; export default { name: "App", components: { HelloWorld, }, mounted() { this.print(); }, methods: { print() { html2canvas(document.querySelector("#printTemplate")).then((canvas) => { const h1tag = document.createElement("h1"); h1tag.className = "heading"; h1tag.innerText = "Output"; document.body.appendChild(h1tag); document.body.appendChild(canvas); document.getElementById("printTemplate").style.opacity = '0.5'; }); }, }, }; </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } h1.heading { text-align: center; color: red; padding-top: 1.5rem; } </style>
Code in Action: