beginPath() in Coffeescript?

beginPath() in Coffeescript?

本文关键字:Coffeescript in beginPath      更新时间:2023-09-26

希望使用coffeescript操作html5画布。

正在寻找jQuery beginPath()的模拟程序,但我在互联网上找不到。

如何在coffeescript中使用beginPath()?谢谢你的任何想法!

下面是来自(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

beginPath不是window上的方法,因此您不能在JavaScript或CoffeeScript中调用beginPath()(当然也不能在jQuery中调用)。相反,beginPath是HTMLCanvas上下文上的一个方法。您可以通过选择您关心的画布来访问上下文:

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

您需要访问索引[0],以确保处理的是HTMLCanvas本身,而不是jQuery对象或NodeList。然后你可以访问它的上下文:

ctx = canvas.getContext '2d'

任何要绘制的图形都需要从上下文对象(例如ctx.beginPath())完成