-
Notifications
You must be signed in to change notification settings - Fork 30
/
canvas-area.html
87 lines (78 loc) · 2.88 KB
/
canvas-area.html
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
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<title>canvas-area</title>
</head>
<body>
<canvas-area id="ca"
width="401"
height="301"
cartesian="false"
resizable="both"
style="background-color:#eee; border:solid 1px black;">
<canvas id="c" style="background-color:transparent;"></canvas>
</canvas-area>
<span id="coords">pos: ./.</span> <b>|</b> <span id="size">size: ./.</span> <b>|</b>
<label><input type="checkbox" onchange="toggleCartesian();"> cartesian</label>
<script src="canvas-area.js"></script>
<script>
const ctx = document.getElementById('c').getContext('2d'),
ca = document.getElementById('ca'),
coords = document.getElementById('coords'),
size = document.getElementById('size'),
toggleCartesian = (e) => { ca.cartesian = !ca.cartesian };
function draw(ctx, view) {
let w = ctx.canvas.width, h = ctx.canvas.height,
sz = 20*view.scl, xoff = view.x%sz, yoff = view.y%sz;
if (ca.cartesian)
ctx.setTransform(1,0,0,-1,0.5,h-0.5);
else
ctx.setTransform(1,0,0,1,0.5,0.5);
ctx.clearRect(0,0,w,h);
// draw grid ...
if (view.scl > 0.2) {
ctx.strokeStyle = "#ccc";
ctx.lineWidth = 1;
ctx.beginPath();
for (let x=xoff,nx=w+1; x<nx; x+=sz) { ctx.moveTo(x,0); ctx.lineTo(x,h); }
for (let y=yoff,ny=h+1; y<ny; y+=sz) { ctx.moveTo(0,y); ctx.lineTo(w,y); }
ctx.stroke();
ctx.strokeStyle = "#555"; // origin lines ...
ctx.beginPath();
ctx.moveTo(view.x,0); ctx.lineTo(view.x,h);
ctx.moveTo(0,view.y); ctx.lineTo(w,view.y);
ctx.stroke();
}
// draw rectangles ...
ctx.save();
if (ca.cartesian)
ctx.setTransform(view.scl,0,0,-view.scl,view.x+0.5,h-view.y-0.5);
else
ctx.setTransform(view.scl,0,0,view.scl,view.x+0.5,view.y+0.5);
ctx.strokeStyle = "#555";
ctx.fillStyle = "#dedede";
ctx.fillRect(60,40,80,60);
ctx.strokeRect(60,40,80,60);
ctx.fillStyle = "orange";
ctx.fillRect(80,100,40,30);
ctx.strokeRect(80,100,40,30);
ctx.restore();
}
function render() {
draw(ctx, ca.view);
requestAnimationFrame(render);
}
window.onload = () => {
ca.on('pointer', e => {
let {x,y} = ca.pntToUsr(e),
prec = Math.max(Math.log(ca.view.scl)/Math.log(2), 0);
coords.innerHTML = `pos: ${(x).toFixed(prec)} / ${(y).toFixed(prec)}`;} )
.on('resize', e => {
size.innerHTML = `size: ${(e.width).toFixed()} / ${(e.height).toFixed()}`; });
ca.resize({width,height}=ca); // cause single initial notification ..
render();
}
</script>
</body>
</html>