0xfe / vexflow

A JavaScript library for rendering music notation and guitar tablature.
http://www.vexflow.com
Other
3.92k stars 663 forks source link

enhancement: also accept canvas context instead of HTMLElement. #655

Closed ritz078 closed 3 years ago

ritz078 commented 6 years ago

This will enable usage of this library in web workers using the OffscreenCanvas API.

More about this has been discussed here.

The only limitation right now is that this library depends on DOM access. Once it is enabled to accept canvas context, we can move this to web worker and control the canvas from there.

I can create a PR.

turnerhayes commented 5 years ago

Have you managed to put together a PR for this?

sschmidTU commented 5 years ago

Demand for this is also high at OSMD. Someone should implement Canvas Context or Web Worker support for Vexflow some day, OSMD will follow :) This would help mobile development with Vexflow/OSMD a lot, because right now we need a DOM element (<div>) to render, and that doesn't integrate well on Mobile.

0xfe commented 5 years ago

I think the following would just work. Can someone try it out?

VF = Vex.Flow;
ctx = VF.Renderer.bolsterCanvasContext(YOUR_CANVAS_CONTEXT)

// Create a stave of width 400 at position 10, 40 on the canvas.
var stave = new VF.Stave(10, 40, 400);

// Add a clef and time signature.
stave.addClef("treble").addTimeSignature("4/4");

// Connect it to the rendering context and draw!
stave.setContext(context).draw();
turnerhayes commented 5 years ago

So the good news is that offscreen canvas does indeed seem to work; I've put together a little repo with a simple demo of it: https://turnerhayes.github.io/vexflow-offscreen-canvas

The bad news is that VexFlow doesn't work (out of the box) in a Worker process; it references window. I was able to work around that by doing var window = self; in the worker file before importing VexFlow, but it would be better if VexFlow itself were adjusted to work in both main and Worker threads. With that little hack, it seems to work (although I tried adding a bunch of notes in the worker thread to test the use case in which a lot of work is being done on a score, but I don't know enough about how VexFlow works to do that)