2016-12-16 52 views
2

私はページが1280x768です。次のコードは1280x768のフルページスナップショットを作成していますが、トップ10pxから、左側10pxから10px、右側10pxを無視する必要があります。html2canvas - 自動トリミングを行うには、上、左、下、右をどのように定義するのですか?

document.body.appendChild(canvas);の前または後に、そのクロップ/スケールなどを行うことはできますか? CSS3やJSなどを使っていますか?

window.takeScreenShot = function() { 
    html2canvas(document.getElementById("top"), { 
     onrendered: function (canvas) { 
      document.body.appendChild(canvas); 
     }, 
     width:1280, 
     height:768 
    }); 
}; 

答えて

3

オフスクリーンキャンバスを使用すれば、レンダリングされたキャンバスを目的のオフセットで描画できます。

すべての要件を満たしていない可能性がありますが、少なくともあなたにアイデアを与えることができる、すぐに書かれた関数です: latest html2canvas version (0.5.0-beta4)を使用します。これはPromiseを返します。

function screenshot(element, options = {}) { 
    // our cropping context 
    let cropper = document.createElement('canvas').getContext('2d'); 
    // save the passed width and height 
    let finalWidth = options.width || window.innerWidth; 
    let finalHeight = options.height || window.innerHeight; 
    // update the options value so we can pass it to h2c 
    if (options.x) { 
    options.width = finalWidth + options.x; 
    } 
    if (options.y) { 
    options.height = finalHeight + options.y; 
    } 
    // chain h2c Promise 
    return html2canvas(element, options).then(c => { 
    // do our cropping 
    cropper.canvas.width = finalWidth; 
    cropper.canvas.height = finalHeight; 
    cropper.drawImage(c, -(+options.x || 0), -(+options.y || 0)); 
    // return our canvas 
    return cropper.canvas; 
    }); 
}  

そしてstacksnippets®がそのフレームにいくつかの強力なセキュリティを使用しているので、私たちはここでライブデモを作ることはできませんが、この内の1つを見つけることができる

screenshot(yourElement, { 
    x: 20, // this are our custom x y properties 
    y: 20, 
    width: 150, // final width and height 
    height: 150, 
    useCORS: true // you can still pass default html2canvas options 
}).then(canvas => { 
    //do whatever with the canvas 
}) 

のようにそれを呼び出しますjsfiddle

ああ、古いhtml2canvasバージョンをサポートしているES5バージョンを望む人は、onrenderedコールバックでクロッピング機能をラップするか、遅いコールバックの場合はa fiddleです。

関連する問題