技術(shù)頻道導(dǎo)航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運(yùn)營

贊助商

分類目錄

贊助商

最新文章

搜索

使用html2canvas網(wǎng)頁截圖并調(diào)整canvas大小

作者:admin    時(shí)間:2021-8-1 20:29:8    瀏覽:

有人提到,使用html2canvas網(wǎng)頁截圖時(shí),希望把canvas的大小進(jìn)行調(diào)整,以更適合內(nèi)容的填充。這其實(shí)可以通過JavaScript來實(shí)現(xiàn),并且實(shí)現(xiàn)起來并不復(fù)雜。


使用html2canvas截圖并調(diào)整canvas大小

demodownload

從本案例看到,canvas的大小區(qū)域發(fā)生了變化,而這一變化是可以通過JavaScript程序來實(shí)現(xiàn)的。

完整HTML代碼

<HTML>
<HEAD>
<TITLE>截圖并調(diào)整canvas大小</TITLE>
<link href="assets/css/style.css" type="text/css" rel="stylesheet" />

<script type="text/javascript" src="node_modules/html2canvas.min.js"></script>
<style type="text/css">
body {margin:30px;}
</style>
</HEAD>


<body>
  <button onclick="screenshot()">點(diǎn)擊截圖</button>
  <div id='input'>
    <h2>這是一個(gè)測試</h2>
    <h3>Hello World</h3> <br>
    Base64 output:
    <input name="screenshot" type='text' id='screenshot_input' /><br><br>
  </div>
  <div id="output">
    <canvas id=c width=100 height=100 style="border:1px solid #000;"></canvas>
  </div>
</body>

<script>
  const canvas = document.getElementById('c');
  const ctx = canvas.getContext('2d');

  function screenshot() {
    html2canvas(document.getElementById('input'), {
      background: '#fff'
    }).then(function(h2c) {
      var base64URL = h2c.toDataURL('image/png').replace('image/png', 'image/octet-stream');
      document.getElementById('screenshot_input').value = base64URL;
      console.log(base64URL);

      canvas.width = h2c.width/5
      canvas.height = h2c.height
      ctx.drawImage(h2c, 0, 0, h2c.width, h2c.height);
    });
  }
</script>
</HTML>

上述代碼,關(guān)鍵的3行代碼為:

canvas.width = h2c.width/5
canvas.height = h2c.height
ctx.drawImage(h2c, 0, 0, h2c.width, h2c.height);

h2chtml2canvas對(duì)象實(shí)例,canvas.width是定義canvas的寬度,canvas.height時(shí)定義canvas的高度;另外,h2c.width是網(wǎng)頁截圖寬度,h2c.height 是網(wǎng)頁截圖高度。大家可以試試更改這幾個(gè)參數(shù)值,看看截圖效果。

此外,drawImage 是調(diào)用的截圖方法。

您可能對(duì)以下文章也感興趣

標(biāo)簽: html2canvas  
相關(guān)文章
    x
    • 站長推薦
    /* 左側(cè)顯示文章內(nèi)容目錄 */