coffeescript画布未画画

时间:2011-12-09 23:40:51

标签: canvas coffeescript

我试图将一小段javascript代码(请参阅注释掉的块)翻译成coffeescript,但画布仍为空。

CoffeeScript的:

class CanvasDrawing
    constructor: (canvasID) ->
        @canvas = document.getElementById(canvasID)
        @context = @canvas.getContext "2d"

    drawLine: ->
        y = 5/8 * @canvas.height

        @context.beginPath()
        @context.moveTo 0, @y
        @context.lineTo @canvas.width, @y
        @context.closePath()
        @context.stroke()
        pos = 
            start: 
                x: 0
                y: @y
            end: 
                x: @canvas.width
                y: @y

    window.CanvasDrawing = CanvasDrawing

HTML / JavaScript的:

<!DOCTYPE html>
    <head>
        <title>CanvasDrawing</title>
        <script type="text/javascript" src="CanvasDrawing.js"></script>
    </head>

    <body>
        <canvas id="canvas" style="width: 500px; height: 500px; border: 1px solid"></canvas>

        <script type="text/javascript">
            var canvasDrawing = new CanvasDrawing("canvas");
            canvasDrawing.drawLine();
        </script>

        <!--
        <script type="text/javascript">
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext('2d');

            context.beginPath();
            context.moveTo(0, 5/8 * canvas.height);
            context.lineTo(canvas.width, 5/8 * canvas.height);
            context.closePath();
            context.stroke();
        </script>
        -->
    </body>
</html>

注释掉的javascript代码并不能产生漂亮的输出,但它可以在Chrome中运行。 我错过了什么?

2 个答案:

答案 0 :(得分:2)

您忘记将y指定为实例的属性,因此传递给绘图函数的@y参数是 undefined

@y = 5/8 * @canvas.height

无关:您可以声明class window.CanvasDrawing并抛弃最后一行。

答案 1 :(得分:1)

我认为问题只是你写的

timeline.drawLine();

当你意味着

canvasDrawing.drawLine();