|
1 <!DOCTYPE html> |
|
2 <html> |
|
3 <head> |
|
4 <title>Custom Elements</title> |
|
5 <script type="text/javascript" src="../../d3.js"></script> |
|
6 <style type="text/css"> |
|
7 |
|
8 body { |
|
9 margin: 0; |
|
10 } |
|
11 |
|
12 </style> |
|
13 </head> |
|
14 <body> |
|
15 <script type="text/javascript"> |
|
16 |
|
17 // Register the "custom" namespace prefix for our custom elements. |
|
18 d3.ns.prefix.custom = "http://github.com/mbostock/d3/examples/dom"; |
|
19 |
|
20 var w = 960, |
|
21 h = 500; |
|
22 |
|
23 // Add our "custom" sketch element to the body. |
|
24 var sketch = d3.select("body").append("custom:sketch") |
|
25 .attr("width", w) |
|
26 .attr("height", h) |
|
27 .call(custom); |
|
28 |
|
29 // On each mouse move, create a circle that increases in size and fades away. |
|
30 d3.select(window).on("mousemove", function() { |
|
31 sketch.append("custom:circle") |
|
32 .attr("x", d3.event.clientX) |
|
33 .attr("y", d3.event.clientY) |
|
34 .attr("radius", 0) |
|
35 .attr("strokeStyle", "red") |
|
36 .transition() |
|
37 .duration(2000) |
|
38 .ease(Math.sqrt) |
|
39 .attr("radius", 200) |
|
40 .attr("strokeStyle", "white") |
|
41 .remove(); |
|
42 }); |
|
43 |
|
44 function custom(selection) { |
|
45 selection.each(function() { |
|
46 var root = this, |
|
47 canvas = root.parentNode.appendChild(document.createElement("canvas")), |
|
48 context = canvas.getContext("2d"); |
|
49 |
|
50 canvas.style.position = "absolute"; |
|
51 canvas.style.top = root.offsetTop + "px"; |
|
52 canvas.style.left = root.offsetLeft + "px"; |
|
53 |
|
54 // It'd be nice to use DOM Mutation Events here instead. |
|
55 // However, they appear to arrive irregularly, causing choppy animation. |
|
56 d3.timer(redraw); |
|
57 |
|
58 // Clear the canvas and then iterate over child elements. |
|
59 function redraw() { |
|
60 canvas.width = root.getAttribute("width"); |
|
61 canvas.height = root.getAttribute("height"); |
|
62 for (var child = root.firstChild; child; child = child.nextSibling) draw(child); |
|
63 } |
|
64 |
|
65 // For now we only support circles with strokeStyle. |
|
66 // But you should imagine extending this to arbitrary shapes and groups! |
|
67 function draw(element) { |
|
68 switch (element.tagName) { |
|
69 case "circle": { |
|
70 context.strokeStyle = element.getAttribute("strokeStyle"); |
|
71 context.beginPath(); |
|
72 context.arc(element.getAttribute("x"), element.getAttribute("y"), element.getAttribute("radius"), 0, 2 * Math.PI); |
|
73 context.stroke(); |
|
74 break; |
|
75 } |
|
76 } |
|
77 } |
|
78 }); |
|
79 }; |
|
80 |
|
81 </script> |
|
82 </body> |
|
83 </html> |