画布高度适合内容

时间:2015-02-26 12:23:59

标签: javascript jquery html html5 canvas

我问了一个类似的问题,尽管假装没有回答我的问题,但它被标记为傻瓜。

编辑:这个骗局是[stackoverflow.com/questions/17211920/make-canvas-height-auto] [1]

我使用画布打印热敏收据,您可能会想到收据的高度可能会有所不同,具体取决于收据上的物品数量。

我需要画布调整内容。

我知道canvas.height = window.innerHeight和类似但我不知道这对我有什么帮助。

HTML

<body onload='onDrawReceipt(shipment, returns, company, customer, img)'>
<form onsubmit='return false;'>
    <table id= "thermal-receipt-table" style='width:100%;'>
        <tbody>
            <tr >
                <td colspan='2' class='left'>
                    <div id='canvasFrame'>
                        <canvas id='canvasPaper' width='576' height= '640' >

                        </canvas>
                    </div>

                </td>
            </tr>

        </tbody>
    </table>
</form>

JS

function onDrawReceipt(order, returns, company, customer, img) {
    var canvas = document.getElementById('canvasPaper');

if (canvas.getContext) {
        var context = canvas.getContext('2d');

        context.clearRect(0, 0, canvas.width, canvas.height);

        context.textBaseline = 'top';

        lineSpace      =  20;
        leftPosition   =  0;
       //centerPosition =  canvas.width       / 2;
        centerPosition = (canvas.width + 26) / 2;
       //rightPosition  =  canvas.width;
        rightPosition  = (canvas.width - 0);

//      cursor = 0;
        cursor = 80;

//rest of code taking content to more than 640px in height.

}

1 个答案:

答案 0 :(得分:0)

您可以依赖contentContainerNode.offsetHeight

var canvas = document.getElementById('canvasPaper')
var contentContainerNode = document.getElementById('myContentContainer')
canvas.height = contentContainerNode.offsetHeight