SVG.Js事件示例,简单绑定拖动操作
一、代码:
var draw = SVG('container').size(300, 300); draw.style({ border: '1px solid red' }); var group = draw.group(); var rect = draw.rect(100, 60).fill('green'); rect.radius(50); group.add(rect); var text = draw.text('测试按钮'); text.style({ fill: 'red', }); text.path('M0,10 100,10').attr({ fill: 'none' }); text.textPath().attr({ startOffset: '50%', 'text-anchor': 'middle', 'dominant-baseline': 'middle' }); group.add(text); group.move(150, 100); group.on('mouseenter', function () { rect.fill('blue'); }).on('mouseleave', function () { rect.fill('green'); }); //鼠标拖动处理 var isMove = false; var spanX = 0; var spanY = 0; group.on('mousedown', function (e) { isMove = true; spanX = e.pageX - group.x(); spanY = e.pageY - group.y(); console.info(spanX); }).on('mouseup', function (e) { isMove = false; }).on('mousemove', function (e) { if (isMove) { //移动等距离的group var tempX = e.pageX - spanX; var tempY = e.pageY - spanY; group.move(tempX, tempY); } });
也可以追加触屏拖动代码:
//绑定触屏操作 group.on('touchstart', function (e) { console.info(e); isMove = true; spanX = e.touches[0].pageX - group.x(); spanY = e.touches[0].pageY - group.y(); console.info(spanX); }).on('touchend', function (e) { isMove = false; }).on('touchmove', function (e) { if (isMove) { //移动等距离的group var tempX = e.touches[0].pageX - spanX; var tempY = e.touches[0].pageY - spanY; group.move(tempX, tempY); } });
结果:
更多: