-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathCanvas.svelte
103 lines (85 loc) · 1.82 KB
/
Canvas.svelte
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<script>
import { onMount } from "svelte";
export let color;
export let size;
export function clear() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
let canvas;
let context;
let previous;
function get_coords(e) {
const { clientX, clientY } = e;
const { left, top } = canvas.getBoundingClientRect();
const x = clientX - left;
const y = clientY - top;
return { x, y };
}
onMount(() => {
context = canvas.getContext('2d');
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resize);
resize();
return () => {
window.removeEventListener('resize', resize);
};
});
</script>
<canvas
bind:this={canvas}
on:pointerdown={(e) => {
const coords = get_coords(e);
context.fillStyle = color;
context.beginPath();
context.arc(coords.x, coords.y, size / 2, 0, 2 * Math.PI);
context.fill();
previous = coords;
}}
on:pointerleave={() => {
previous = null;
}}
on:pointermove={(e) => {
const coords = get_coords(e);
if (e.buttons === 1) {
e.preventDefault();
context.strokeStyle = color;
context.lineWidth = size;
context.lineCap = 'round';
context.beginPath();
context.moveTo(previous.x, previous.y);
context.lineTo(coords.x, coords.y);
context.stroke();
}
previous = coords;
}}
></canvas>
{#if previous}
<div
class="preview"
style="--color: {color}; --size: {size}px; --x: {previous.x}px; --y: {previous.y}px"
></div>
{/if}
<style>
canvas {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.preview {
position: absolute;
left: var(--x);
top: var(--y);
width: var(--size);
height: var(--size);
transform: translate(-50%, -50%);
background: var(--color);
border-radius: 50%;
opacity: 0.5;
pointer-events: none;
}
</style>