Print out section of html5 canvas
我有一个html5画布(3000像素x 3000像素)。我正在使用以下功能来打印画布:
1 2 3 4 5 6 | function printCanvas() { popup = window.open(); popup.document.write(" <img src='"+canvas.toDataURL('png')+"'/>"); popup.print(); } |
问题是,如果我在画布上只有一个元素(例如一个圆圈)并按print,它将尝试打印出整个画布(3000 x 3000)。有没有一种方法可以更改它,使其仅打印画布的特定部分,或者仅打印存在元素的部分,而不会打印出空白。
谢谢。
另一个答案描述了正确的方法。主要问题是找到界限。我得到所有图像数据,并在两个for循环中找到边界:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | function getCanvasBorders(canvas) { var topleft = {x: false, y: false}; var botright = {x: false, y: false}; for(var x = 0; x < canvas.width; x++) { for(var y = 0; y < canvas.height; y++) { if(!emptyPixel(context, x, y)) { if(topleft.x === false || x < topleft.x) { topleft.x = x; } if(topleft.y === false || y < topleft.y) { topleft.y = y; } if(botright.x === false || x > botright.x) { botright.x = x; } if(botright.y === false || y > botright.y) { botright.y = y; } } } } return {topleft: topleft, botright: botright}; } |
SO片段无法与
假设您有一种跟踪和重绘对象的方法,则可以执行以下操作:
打印临时画布。
更新:假设背景透明,仅查找图像内容的边缘,请参见此答案。