@alegendstale/holly-components
Version:
Reusable UI components created using lit
69 lines (68 loc) • 2.62 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import colorsea from '../../utils/colorsea-wrapper.js';
import { EventEmitter } from '../../utils/EventEmitter.js';
import { ref } from 'lit/directives/ref.js';
import { LitElement, html, css } from 'lit';
import { query } from 'lit/decorators.js';
import { condCustomElement } from '../../decorators/condCustomElement.js';
let CanvasBase = class CanvasBase extends LitElement {
constructor() {
super(...arguments);
this.emitter = new EventEmitter();
}
disconnectedCallback() {
super.disconnectedCallback();
this.emitter.clear();
}
render() {
let canvasRef = (canvas) => {
if (!(canvas instanceof HTMLCanvasElement))
return;
this.context = canvas.getContext('2d', { willReadFrequently: true, alpha: true });
};
return html `
<canvas
@click=${(e) => this.emitter.emit('click', this.getCanvasHex(e.clientX, e.clientY))}
@pointermove=${(e) => {
// Track only the first touch
if (!e.isPrimary)
return;
this.emitter.emit('move', { x: e.clientX, y: e.clientY });
}}
${ref(canvasRef)}
>
</canvas>
`;
}
// Retrieves the hex from the mouse position
getCanvasHex(clientX, clientY) {
const canvasBounds = this.canvas.getBoundingClientRect();
let x = clientX - canvasBounds.left;
let y = clientY - canvasBounds.top;
let [r, g, b, a] = this.context.getImageData(x, y, 1, 1).data;
// Convert alpha from 0-255 to 0-1
const alpha = Math.round((a / 255) * 100);
// Hide alpha value if not an alpha color
let hex = alpha !== 255 ? colorsea([r, g, b, alpha]).hex() : colorsea([r, g, b]).hex();
return hex;
}
};
CanvasBase.styles = [
css `
:host {
display: block;
}
`
];
__decorate([
query('canvas')
], CanvasBase.prototype, "canvas", void 0);
CanvasBase = __decorate([
condCustomElement('canvas-base')
], CanvasBase);
export { CanvasBase };