encapsulate canvas logic

This commit is contained in:
Felix Roos 2024-03-15 01:47:35 +01:00
parent 48e0691eec
commit 83ea3bb138
3 changed files with 25 additions and 19 deletions

View File

@ -0,0 +1,21 @@
import { customElement } from 'solid-element';
customElement('strudel-canvas', {}, () => {
return <canvas width={300} height={200} />;
});
export function getWidgetDrawContext(id, options) {
let el = document.getElementById(id);
if (!el) {
console.warn(`widget with id ${id} not found in the DOM`);
return;
}
const { width = 300, height = 100, pixelRatio = window.devicePixelRatio } = options || {};
const canvas = el?.shadowRoot.firstChild;
canvas.width = width * pixelRatio;
canvas.height = height * pixelRatio;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
const ctx = canvas.getContext('2d');
return ctx;
}

View File

@ -1,29 +1,13 @@
import { Pattern } from '@strudel/core';
import { registerWidget } from '@strudel/transpiler';
import { customElement } from 'solid-element';
import { getWidgetDrawContext } from './Canvas.jsx';
customElement('strudel-pianoroll', { options: JSON.stringify('{}') }, (props, { element }) => {
return <canvas width={400} height={100} />;
});
registerWidget('roll', 'strudel-pianoroll');
registerWidget('roll', 'strudel-canvas');
Pattern.prototype.roll = function (id, options = { fold: 1 }) {
// TODO: remove setTimeout...
setTimeout(() => {
let el = document.getElementById(id);
if (!el) {
console.log('widget not found...');
return this;
}
const { width = 400, height = 100 } = options;
const canvas = el?.shadowRoot.firstChild;
const pixelRatio = window.devicePixelRatio;
canvas.width = width * pixelRatio;
canvas.height = height * pixelRatio;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
const ctx = canvas.getContext('2d');
const ctx = getWidgetDrawContext(id, options);
this.pianoroll({ ...options, ctx });
});
return this;

View File

@ -1,2 +1,3 @@
export * from './Claviature.jsx';
export * from './Pianoroll.jsx';
export * from './Canvas.jsx';