Canvas / SVG Hit Testing
This Fiddle shows how to use the same data-models from Two.js to draw two separate layers. A layer with canvas for particle movement and fast drawing and an SVG layer for minimal objects and hit-testing through native html event listeners.
by jonobr1
HTML
<script src="http://jonobr1.github.com/two.js/third-party/two.js"></script>
JavaScript
var two = new Two({
type: Two.Types.canvas,
fullscreen: true,
autostart: true
}).appendTo(document.body);
var svg = new Two({
fullscreen: true,
autostart: true
}).appendTo(document.body);
var center = svg.makeCircle(two.width / 2, two.height / 2, 100);
center.noStroke().fill = 'rgb(100, 100, 255)';
var circles = [];
for (var i = 0; i < 10; i++) {
var circle = two.makeCircle(0, 0, 15);
circle.noStroke().fill = 'rgb(100, 100, 255)';
circle.offset = Math.random() * 1000;
circle.radius = Math.random() * two.height / 4 + two.height / 4;
circle.theta = Math.random() * Math.PI * 2;
circles.push(circle);
}
svg.update();
center._renderer.elem.addEventListener('mouseover', function() {
changeColor('rgb(255, 100, 100)');
}, false);
center._renderer.elem.addEventListener('mouseout', function() {
changeColor('rgb(100, 100, 255)');
}, false);
two.bind('update', function(frameCount) {
center.translation.set(two.width / 2, two.height / 2);
center.scale = 0.5 * (Math.sin(frameCount / 30) + 1) / 2 + 0.5;
for (var i = 0; i < circles.length; i++) {
var circle = circles[i];
var mag = circle.radius * Math.sin(circle.offset + frameCount / 15);
var x = mag * Math.cos(circle.theta) + center.translation.x;
var y = mag * Math.sin(circle.theta) + center.translation.y;
circle.translation.set(x, y);
}
});
function changeColor(color) {
center.fill = color;
for (var i = 0; i < circles.length; i++) {
circles[i].fill = color;
}
}