canvas widget: pretty much working

This commit is contained in:
jean-emmanuel 2021-12-06 12:01:05 +01:00
parent df101eac0e
commit 3a872f6920
7 changed files with 213 additions and 38 deletions

View file

@ -0,0 +1,92 @@
# Canvas widget
The canvas widget allows creating custom widgets with user-defined drawings and touch reactions.
It has two special properties, `touch` and `draw`, that work like the `script` property : they are used to defined scripts that will be executed when specific events occurs.
This widget requires a good understanding of the javascript [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) and of the javascript programming language in general.
## `touch`
This script is executed when the wigdget is touched, when it is released, and during the movement of the pointer while the widget is touched.
This script has access to the same variables and functions as the `script` property (except the event-specific ones), plus the following:
- `width`: widget width in pixels
- `height`: widget height in pixels
- `event`: object containing the following:
- `type`: `"start"`, `"move"` or `"stop"`
- `target`: id of the widget under the pointer, `"this"` if it's the canvas widget itself, `null` if no widget is under the pointer
- `offsetX`, `offsetY`: touch coordinates in pixels, relative to `target`
- `movementX`, `movementY`: movement of the pointer in pixels since the last event
- `pointerId`: unique identifier used to differenciates fingers in multitouch situation
- `altKey`, `ctrlKey`, `shiftKey`: keyboard modifier states
## `draw`
This script is executed when the widget should be redrawn, which is when it's touched and when it receives a value. If the `continuous` property is enabled, the widget will be redrawn at a fixed rate even if not interacted with.
This script has access to the same variables and functions as the `script` property (except the event-specific ones), plus the following:
- `width`: widget width in pixels
- `height`: widget height in pixels
- `ctx`: [canvas rendering context](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D) of the widget
- `cssVars`: object containing the computed value of some of the widget's style properties such as `colorWidget`, `alphaFill`, `padding`, etc
## Example
Let's create a simple xy pad, with a value made of two numbers between 0 and 1.
First, we use the `touch` property to store the touch coordinates in the `locals` object. We also call `set()` to store these in the widget's value?
```js
// touch property
// store normalized coordinates
if (event.type == "start") {
locals.dx = event.offsetX / width
locals.dy = event.offsetY / height
} else {
// when the pointer is moving, increment coordinates
// because offsetX and offsetY may not be relevant
// if the pointer hovers a different widgets
locals.dx += event.movementX / width
locals.dy += event.movementY / height
}
// locals.dx and locals.dy may be under 0 or above 1
// but we want the widget's value and the drawing to
// stay between these limits
locals.x = Math.max(0, Math.min(1, locals.dx))
locals.y = Math.max(0, Math.min(1, locals.dy))
// update widget value and send
set("this", [locals.x, locals.y])
```
Then, we use the `draw` property to draw a circle at the touch coordinates.
```js
// draw property
// draw an arc at touch coordinates
ctx.arc(locals.x * width, locals.y * height, 6, 0, Math.PI * 2)
// use colorFill property as stroke color
ctx.strokeStyle = cssVars.colorFill
// draw stroke
ctx.stroke()
```
Finally, we use the `script` property to make the widget send it's values, and to make sure it updates properly when reveiving.
```js
// script property
// update locals.x and locals.y
// required if we want to update the drawing when receiving osc messages
if (value.length == 2) {
locals.x = value[0]
locals.y = value[1]
}
```

View file

@ -45,6 +45,7 @@ nav:
- docs/widgets/advanced-syntaxes.md
- docs/widgets/scripting.md
- docs/widgets/fragments.md
- docs/widgets/canvas.md
- MIDI:
- MIDI configuration: docs/midi/midi-configuration.md
- MIDI messages: docs/midi/midi-messages.md

View file

@ -99,7 +99,7 @@ var Parser = class Parser {
} else if (defaultValue !== '' && defaultValue !== undefined) {
widget.setValue(defaultValue)
widget.setValue(defaultValue, {defaultInit: true})
}

View file

@ -40,7 +40,7 @@ module.exports.widgets = {
xy: require('./pads/xy'),
rgb: require('./pads/rgb'),
multixy: require('./pads/multixy'),
// canvas: require('./pads/canvas'),
canvas: require('./pads/canvas'),
// sliders
fader: require('./sliders/fader'),
@ -60,7 +60,7 @@ module.exports.categories = {
'Frames':['frame', 'svg', 'html', 'image'],
'Graphs':['plot','eq','visualizer'],
'Indicators':['led', 'text'],
'Pads':['xy','rgb','multixy'],
'Pads':['xy','rgb','multixy', 'canvas'],
'Sliders':['fader','knob', 'encoder', 'range'],
'Scripts':['script', 'variable'],
}

View file

@ -1,11 +1,13 @@
var Canvas = require('../common/canvas'),
Script = require('../scripts/script'),
widgetManager = require('../../managers/widgets'),
html = require('nanohtml')
class CanvasWidget extends Canvas {
static description() {
return 'KANVA !'
return 'Multitouch canvas widget with user-defined drawing functions and touch reactions.'
}
@ -13,8 +15,23 @@ class CanvasWidget extends Canvas {
return super.defaults().extend({
class_specific: {
onCreate: {type: 'string', value: '', help: ' '},
onTouch: {type: 'string', value: '', help: ' '},
// value: {type: 'number', value: 1, help: [
//
// ]},
autoClear: {type: 'boolean', value: true, help: [
'If set to `false`, the canvas context won\'t be cleared automatically and `ctx.clear` will need to be called in `draw`.'
]},
continuous: {type: 'boolean|number', value: false, help: [
'If set to `true`, `draw` will be called at each frame, otherwise it will be called only when the widget is touched and when it receives a value.',
'Can be a number between 1 and 60 to specify the framerate.'
]},
touch: {type: 'string', value: '', help: [
'Script executed when the widget is touched',
'Exposed '
]},
draw: {type: 'string', value: '', help: [
'Script executed when the widget is redrawn.'
]},
}
})
@ -23,74 +40,113 @@ class CanvasWidget extends Canvas {
constructor(options) {
super({...options, html: html`
<div class="canvas">
<inner>
<canvas></canvas>
</div>
</inner>
`})
this.drawScript = new Script({props:{
id: this.getProp('id') + '/drawScript',
script: this.getProp('draw'),
event: {
value: 0,
width: 100,
height: 100,
ctx: {},
cssVars: {}
}
}, builtIn: true, parent: this})
this.touchScript = new Script({props:{
id: this.getProp('id') + '/touchScript',
script: this.getProp('touch'),
event: {
value: 0,
width: 100,
height: 100,
event: {}
}
}, builtIn: true, parent: this})
var touchCb = (e, type)=>{
var event = {...e}
delete event.firstTarget
var w = widgetManager.getWidgetByElement(event.target)
if (w) event.target = w === this ? 'this' : w.getProp('id')
else event.target = null
event.type = type
this.touchScript.run({
value: this.value,
width: this.width,
height: this.height,
event: event,
}, {sync: true, send: true})
this.batchDraw()
}
this.on('draginit',(e)=>{
touchCb(e, 'start')
}, {element: this.widget, multitouch: true})
this.on('drag',(e)=>{
touchCb(e, 'move')
}, {element: this.widget, multitouch: true})
this.on('dragend',(e)=>{
touchCb(e, 'stop')
}, {element: this.widget, multitouch: true})
if (this.getProp('continuous')) {
var freq = parseInt(this.getProp('continuous')) || 30
freq = Math.max(Math.min(60, freq), 1)
this.drawInterval = setInterval(()=>{
this.batchDraw()
}, 1000/freq)
}
}
setValue(v, options={}) {
if (v === null || v === undefined || ((v.length || 1) !== this.getProp('valueLength'))) return
this.value = v
if (!options.dragged) {
var coords = this.resolveProp('valueToCoords', undefined, false, false, false, {
coords: this.touchCoords,
value: this.value,
width: this.width,
height: this.height,
local: this.localContext
}) || this.touchCoords
this.touchCoords = coords === undefined ? this.touchCoords : coords
}
this.batchDraw()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
if (options.defaultInit) this.script.setValue(this.value, {id: this.getProp('id')})
}
draw() {
if (this.getProp('autoClear')) this.clear()
if (this.getProp('autoClear')) {
this.clear()
this.ctx.beginPath()
}
this.resolveProp('draw', undefined, false, false, false, {
ctx: this.ctx,
coords: this.touchCoords,
this.drawScript.run({
value: this.value,
colors: this.colors,
ctx: this.ctx,
width: this.width,
height: this.height,
})
if (this.getProp('autoClear')) this.clearRect = [0, 0, this.width, this.height]
cssVars: this.cssVars
}, {sync: false, send: false})
this.batchDraw()
}
onRemove() {
clearInterval(this.drawInterval)
super.onRemove()
}
}

View file

@ -88,6 +88,8 @@ class Script extends Widget {
})
} else if (typeof this.getProp('event') === 'object'){
this.compile(this.getProp('event'))
}
}

View file

@ -1,6 +1,7 @@
.xy-container,
.multixy-container,
.rgb-container {
.rgb-container,
.canvas-container {
width: 200rem;
height: 200rem;
}
@ -125,3 +126,26 @@
}
}
.canvas-container {
--alpha-fill-off: 0.05;
--alpha-fill: var(--alpha-fill-off);
--widget-padding: 0rem;
inner {
position: relative;
flex: 1;
display: flex;
@include pseudo-fill($z: -1);
@include pseudo-stroke();
}
canvas {
width: 100%;
text-align: center;
}
}