I’m trying to translate a little piece of javascript code (see commented out block) into coffeescript, but the canvas remains empty.
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>
The commented out javascript code doesn’t produce pretty output, but it works in Chrome.
What am I missing?
You forgot to assign
yas a property of the instance, so the@yargument passed to the drawing functions is undefined.Unrelated: you can declare
class window.CanvasDrawingand ditch that last line.