0

I have managed to create and add a canvas element to a FramerJS prototype:

myCanvas = document.createElement "canvas"
myCanvas.setAttribute("width","750px")
myCanvas.setAttribute("height","500px")
myCanvas.setAttribute("style","border: 2px solid black; background: #CCC")

container = new Layer
    height: 1334
    width: 750
    backgroundColor: "white"
    html: myCanvas.outerHTML
ctx = myCanvas.getContext "2d"

ctx.fillStyle = "blue"
ctx.fillRect(0, 0, 50, 50)

If you print(ctx) it shows a valid CanvasRenderingContext2D as the output. The problem is, nothing happens on the prototype. It remains blank - like the fillRect function was never called.

Need to confirm if this is do to lack of support or if I'm doing something wrong.

ortonomy
  • 653
  • 10
  • 18

1 Answers1

1

By setting the html of the layer to the canvas html, you're losing the reference to the canvas you created. So the fillRect is called, but not on the canvas you actually see :)

If you remove the html property and instead do:

container._element.appendChild(myCanvas)

The reference to your canvas remains and you're actually drawing on the canvas that is displayed.

Full example:

myCanvas = document.createElement "canvas"
myCanvas.setAttribute("width","750px")
myCanvas.setAttribute("height","500px")
myCanvas.setAttribute("style","border: 2px solid black; background: #CCC")

container = new Layer
    height: 1334
    width: 750
    backgroundColor: "white"

container._element.appendChild(myCanvas)
ctx = myCanvas.getContext "2d"

ctx.fillStyle = "blue"
ctx.fillRect(0, 0, 50, 50)

Framer project: http://share.framerjs.com/v4a1eyjv806s/

Niels
  • 771
  • 5
  • 5
  • This worked! I don't want to answer my own question with a better answer, but with your hint about '_element' I figured I'd google 'canvas' and '_element' and found a Github Gist from a framer guy, 'koenbok' that gives an EXACT example of getting the canvas to work in Framer JS. If you want to update your question with more details from here: https://gist.github.com/koenbok/7012440, I'll accept your answer! – ortonomy Sep 02 '16 at 14:45
  • Did you see the link to the framer project I posted? That contains pretty much the exact same code. I've updated the answer to include that code inline now. – Niels Sep 04 '16 at 18:16