Nick Bewley
Nick Bewley

Reputation: 9289

beginPath() in Coffeescript?

Looking to manipulate html5 canvas using coffeescript.

Looking for an analog to jQuery beginPath(), but I haven't been able to find one on the internet.

How can I use beginPath() in coffeescript? Thanks for any ideas!

Upvotes: 0

Views: 145

Answers (2)

elreimundo
elreimundo

Reputation: 6276

beginPath is not a method on window, so you can't call beginPath() in either JavaScript or in CoffeeScript (and certainly not in jQuery). Instead, beginPath is a method on an HTML Canvas context. You can access a context by selecting the canvas you care about:

canvas = document.getElementsByTagName('canvas')[0]

You need to access the index [0] to make sure you're dealing with the HTML Canvas itself, rather than a jQuery object or a NodeList. Then you can access its context:

ctx = canvas.getContext '2d'

Any drawing you want to do needs to be done from the context object (e.g. ctx.beginPath())

Upvotes: 0

anchor
anchor

Reputation: 815

Here is an example "Seed Of Life" from (http://autotelicum.github.io/Smooth-CoffeeScript/interactive/interactive-coffeescript.html)

webdesign = -> 
  doctype 5
  html ->
    head ->
      meta charset: 'utf-8'
      title 'My drawing | My awesome website'
      style '''
        body {font-family: sans-serif}
        header, nav, section, footer {display: block}
      '''
      coffeescript ->
        draw = (ctx, x, y) ->
          circle = (ctx, x, y) ->
            ctx.beginPath()
            ctx.arc x, y, 100, 0, 2*Math.PI, false
            ctx.stroke()
          ctx.strokeStyle = 'rgba(255,40,20,0.7)'
          circle ctx, x, y
          for angle in [0...2*Math.PI] by 1/3*Math.PI
            circle ctx, x+100*Math.cos(angle),
                        y+100*Math.sin(angle)
        window.onload = ->
          canvas = document.getElementById 'drawCanvas'
          context = canvas.getContext '2d'
          draw context, 300, 200
    body ->
      header -> h1 'Seed of Life'
      canvas id: 'drawCanvas', width: 550, height: 400

Upvotes: 1

Related Questions