События не работающие на SVG, сделанные с Snap.svg - PullRequest
0 голосов
/ 08 января 2019

Здравствуйте, мои коллеги разработчики кода.

Я пытаюсь реализовать плавающий значок меню, используя Snap.svg. У меня возникла проблема, когда я могу нарисовать значок, но не могу зафиксировать какие-либо события на значке. Я нахожу, что если я не наложу все свои svg, тогда я могу щелкнуть по нему, но я не хочу, чтобы это имело место в макете.

Ниже приведен мой код и скрипта JS, где я тестирую, чтобы посмотреть, смогу ли я просто изменить цвет графики на черный после нажатия на нее.

/* HTML containers */
const menuDIV = document.getElementById("MENU");
menuDIV.style.opacity = 1.0;
menuDIV.hidden = false;

const UIDIV = document.getElementById("UI");
UIDIV.hidden = false;

const roomWidth = $(window).width();
const roomHeight = $(window).height();
const origin = {
    x : roomWidth/2,
    y: roomHeight/2
};

/* SVG Stuff */
const menuPaper = Snap(roomWidth,roomHeight);
const UIPaper = Snap(roomWidth,roomHeight);
const smallMenuButtonPaper = Snap(100,100);

$(menuPaper.node).appendTo('#MENU');
$(UIPaper.node).appendTo('#UI');
$(smallMenuButtonPaper.node).appendTo('#UI');

smallMenuButtonPaper.attr({
    id : "small-menu-button",
    class : "overlay"
})

function menuButton(shape){
    this.icon = shape;
    let _this = this;

    /**************************** This is not working */
    function changeColour(){
        _this.icon.attr({
        	fill : "black"
        })
    }
    this.icon.click(changeColour);
};

function drawMenuButton(){
    let rect = smallMenuButtonPaper.rect(10,10,50,50).attr({
    	fill:"red"
    });

    return new menuButton(rect);
}

function hexaFace(face,id,heading,translate){
    this.face = face;
    this.text = heading;
    this.translateDirection = translate;
    this.buttonID = id;
    let _this = this;
    let old_colour = this.face.node.attributes.fill.value;

    function mouseOver(){
        _this.face.animate({
            transform: 't'+ _this.translateDirection[0]+','+_this.translateDirection[1]
          }, 200, mina.linear)
        _this.face.attr({fill:"black"});  
    }

    function mouseOut(){
        _this.face.animate({
            transform: 's1'
          }, 200, mina.linear)
        _this.face.attr({fill:old_colour});
    }
    this.face.hover(mouseOver,mouseOut);
}



function drawHexagonMenu(){
// Draw Hexagonal Menu
    // Draw Hexagon faces from origin
    let vertices = 6; 
    let angleInc = (360/vertices);

    let dist = roomHeight/3;

    let hexagonMenu = new Array(vertices).fill(0).map((_,i)=>{
        let x1 = origin.x + dist*Snap.cos((angleInc/2)*9+angleInc*i);
        let y1 = origin.y + dist*Snap.sin((angleInc/2)*9+angleInc*i);
        let x2 = origin.x + dist*Snap.cos((angleInc/2)*9+angleInc*(i+1));
        let y2 = origin.y + dist*Snap.sin((angleInc/2)*9+angleInc*(i+1));
        let face = menuPaper.polyline(origin.x,origin.y,x1,y1,x1,y1,x2,y2).attr({
            fill : "purple",
            stroke : "white",
            class : "menu-slice"
        });
        
        return new hexaFace(face,i,_,[((x1+x2)/2-origin.x)/5,((y1+y2)/2-origin.y)/5]);
    })

    return hexagonMenu;
}

function drawGrid(){
    let divisor = 10;
    let grid; 
    let noVertLines;
    let noHorizontalLines;
    let strokeWeight;
    // Determine amount of vertical lines 
    let vertLinesIncrement = roomWidth/(roomSize[0]*10);
    let horizontalLinesIncrement = roomHeight/(roomSize[1]*10);
    // Draw lines
    let verticalLines = new Array(roomSize[0]*10).fill(0);
    let horizontalLines = new Array(roomSize[0]*10).fill(0);
    verticalLines = verticalLines.map((x,i)=>{
        if (i%divisor == 0) {
            strokeWidth = "2px"; 
        }
        else {
            strokeWidth = "1px";
        }
        return UIPaper.line(vertLinesIncrement*i,0,vertLinesIncrement*i,roomHeight).attr(
            {stroke : "grey",
            strokeWidth : strokeWidth,
            opacity : 0.75}
        );
    })
    horizontalLines = horizontalLines.map((x,i)=>{
        if (i%divisor == 0) {
            strokeWidth = "2px"; 
        }
        else {
            strokeWidth = "1px";
        }
        return UIPaper.line(0,horizontalLinesIncrement*i,roomWidth,horizontalLinesIncrement*i).attr(
            {stroke : "grey",
             strokeWidth : strokeWidth, 
            opacity : 0.75}
        );
    })
}

function createPrototype(){
    drawGrid();
    let hexagonMenu = drawHexagonMenu();
    drawMenuButton();
}
let roomSize = [10,10,4];   
createPrototype();
.overlay{
    position : absolute;
    /* position : fixed; */
}

#small-menu-button {
    
    top:5px;
    right : 25px;
    position: fixed;
}
<div id="UI" class="overlay"> </div>

</div>

<div id="MENU" class="overlay"> </div>

</div>

JSFiddle

Любая помощь будет принята с благодарностью. Такое ощущение, что это не должно быть слишком сложной проблемой ... Просто что-то частично совпадает или что-то в этом роде, но мои знания CSS и веб-макета недостаточно глубоки, чтобы точно знать, где я ошибаюсь.

1 Ответ

0 голосов
/ 08 января 2019

Я ответил на свой вопрос с помощью моего младшего брата! : D

Я давал своей кнопке меню две разные позиции в CSS, что явно сбивало с толку обработчик событий.

...