Skip to content

Instantly share code, notes, and snippets.

@davinma
Created December 31, 2021 02:44
Show Gist options
  • Save davinma/bbec39bee295fbd7c6dbc271a0511d7f to your computer and use it in GitHub Desktop.
Save davinma/bbec39bee295fbd7c6dbc271a0511d7f to your computer and use it in GitHub Desktop.
html table border to canvas
<!DOCTYPE html>
<html>
<head>
<title>html table border to canvas</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.slim.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/1.3.3/html2canvas.js"></script>
<style>
th, td {
padding: 20px;
background-color: #fff;
}
</style>
</head>
<body>
<center>
<h2 style="color:green">html table border to canvas</h2>
<div id="html-content-holder" style="margin: 0 auto;display: inline-block;background-color: #ccc">
<table border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr>
<th colspan="2">placeholder</th>
<th colspan="2">placeholder</th>
</tr>
<tr>
<th rowspan="2">placeholder</th>
<th>placeholder</th>
<th>placeholder</th>
<th>placeholder</th>
</tr>
<tr>
<th>placeholder</th>
<th>placeholder</th>
<th>placeholder</th>
</tr>
</tbody>
</table>
</div>
<br/>
<br/>
<input id="btn-preview" type="button" value="Preview" />
<a id="btn-download" href="#">Download</a>
<br/>
<h3>Preview :</h3>
<div id="previewImage"></div>
<script>
$(document).ready(function () {
var element = $("#html-content-holder");
var getCanvas;
$("#btn-preview").on('click', function () {
html2canvas(element[0]).then( (canvas)=>{
$("#previewImage").empty().append(canvas);
getCanvas = canvas;
})
});
$("#btn-download").on('click', function () {
var imgageData =
getCanvas.toDataURL("image/png");
var newData = imgageData.replace(
/^data:image\/png/, "data:application/octet-stream");
$("#btn-download").attr({
"download": "canvas_table.png",
"href": newData
});
});
});
</script>
</center>
</body>
</html>
@davinma
Copy link
Author

davinma commented Dec 31, 2021

has a few flaws in Edge and FireFox, but beautiful in Chrome 😂

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment