123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- /* 設置body背景透明 */
- body {
- background-color: transparent;
- margin: 0;
- padding: 0;
- display: flex;
- justify-content: center;
- align-items: center;
- height: 100vh;
- }
- /* 設置容器div背景透明 */
- .chart-container {
- background-color: transparent;
- padding: 20px;
- border-radius: 8px;
- box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
- }
- </style>
- </head>
- <body>
- <div class="chart-container" id="capture">
- <p>透明背景測試</p>
- <canvas id="myChart" width="400" height="400"></canvas>
- </div>
- <br>
- <button id="downloadBtn">Download as Transparent PNG</button>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/chart.js@3.0.0/dist/chart.min.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-3d@1.0.0-beta.2/dist/chartjs-plugin-3d.min.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
- <script>
- // 設定圖表
- const ctx = document.getElementById('myChart').getContext('2d');
- const myChart = new Chart(ctx, {
- type: 'bar',
- data: {
- labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
- datasets: [{
- label: '# of Votes',
- data: [12, 19, 3, 5, 2, 3],
- backgroundColor: [
- 'rgba(255, 99, 132, 0.2)',
- 'rgba(54, 162, 235, 0.2)',
- 'rgba(255, 206, 86, 0.2)',
- 'rgba(75, 192, 192, 0.2)',
- 'rgba(153, 102, 255, 0.2)',
- 'rgba(255, 159, 64, 0.2)'
- ],
- borderColor: [
- 'rgba(255, 99, 132, 1)',
- 'rgba(54, 162, 235, 1)',
- 'rgba(255, 206, 86, 1)',
- 'rgba(75, 192, 192, 1)',
- 'rgba(153, 102, 255, 1)',
- 'rgba(255, 159, 64, 1)'
- ],
- borderWidth: 1
- }]
- },
- options: {
- scales: {
- y: {
- beginAtZero: true
- }
- },
- // 確保背景透明
- plugins: {
- legend: {
- labels: {
- color: 'rgba(0, 0, 0, 1)' // 修改圖例顏色以適應透明背景
- }
- }
- },
- responsive: true,
- maintainAspectRatio: true,
- backgroundColor: 'transparent'
- }
- });
- // 下載圖片按鈕
- document.getElementById('downloadBtn').addEventListener('click', function () {
- const captureElement = document.getElementById('capture');
- html2canvas(captureElement, {
- backgroundColor: null, // 保持背景透明
- useCORS: true // 若有跨域圖片,需設置此選項
- }).then(function (canvas) {
- const link = document.createElement('a');
- link.href = canvas.toDataURL('image/png');
- link.download = 'chart-container.png';
- link.click();
- });
- });
- </script>
- </body>
- </html>
|