2016-12-16 217 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®使用了一些強大的安全性在他們的框架調用它像

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

哦,對於那些想要ES5版本支持舊的html2canvas版本的人,你只需要在回調的回調中包裝裁剪功能,或者對於懶惰的回調,這裏是a fiddle

相關問題