-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshape-canvas.js
74 lines (61 loc) · 1.67 KB
/
shape-canvas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { onDOMChange} from './lib/components'
class TheCircle extends HTMLElement {
// static observedAttributes = ['radius', 'x', 'y']
/**
* @param {{ radius?: number, x?: number, y?: number }} [attrs={}]
*/
constructor(attrs = {}) {
super()
for (const [k, v] of Object.entries(attrs)) {
this.setAttribute(k, v)
}
}
}
class TheCanvas extends HTMLElement {
constructor() {
super()
this.shadow = this.attachShadow({mode: 'open'})
this.shadow.innerHTML = this.template()
this.shadow.addEventListener('click', event => {
this.append(new TheCircle({ radius: 30, x: event.offsetX, y: event.offsetY }))
})
onDOMChange(this, this.render)
}
template() {
return `
<style>
:host {
display: flex;
cursor: crosshair;
}
</style>
<canvas></canvas>
`
}
render() {
const canvas = this.shadow.querySelector('canvas')
canvas.width = canvas.clientWidth
canvas.height = canvas.clientHeight
const ctx = canvas.getContext('2d')
ctx.fillStyle = this.computedStyleMap().get('color')
ctx.strokeStyle = this.computedStyleMap().get('color')
ctx.lineWidth = 5
for (const shape of this.querySelectorAll('shape-circle')) {
const [x, y, radius] = [
shape.getAttribute('x'),
shape.getAttribute('y'),
shape.getAttribute('radius')
]
ctx.beginPath()
ctx.arc(x, y, radius, 0, 2 * Math.PI, true)
ctx.closePath()
ctx.stroke()
}
}
connectedCallback() {
this.render()
}
}
customElements.define('shape-circle', TheCircle)
customElements.define('shape-canvas', TheCanvas)
console.log('👻')