【问题标题】:Canvas height to fit content适合内容的画布高度
【发布时间】:2015-04-28 19:50:43
【问题描述】:

我问了一个类似的问题,尽管假定的受骗者没有回答我的问题,但它被标记为受骗者。

编辑:被骗的是 [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.

}

【问题讨论】:

  • 您也许可以包含骗子并说您尝试了指定的内容。这会让其他人更多地了解你的尝试。
  • 提供一个 jsfiddle 或 pluckr 示例供人们一起玩
  • 我无法提供小提琴,我真的需要帮助。画布高度似乎无法根据内容动态变化
  • 您可以计算所需的高度,调整画布大小,然后绘制内容。
  • 是的,我将如何计算?我会使用什么元素?

标签: javascript jquery html canvas


【解决方案1】:

你可以依赖 contentContainerNode.offsetHeight

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2014-11-08
    相关资源
    最近更新 更多