0

我正在尝试使用鼠标悬停在 svg 元素内创建一个矩形。有时可以,但有时我会收到如下错误:

   >TypeError
   arguments: Array[2]
   get message: function getter() { [native code] }
   get stack: function getter() { [native code] }
   set message: function setter() { [native code] }
   set stack: function setter() { [native code] }
   type: "undefined_method"
   __proto__: Error

这是 Javascript 代码:

    function _click(evt){
    if (cropping){
        if (initial_point == 0){
            console.log('first click');
            rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
            rect.setAttributeNS(null, 'id', 'area');
            svg.appendChild(rect);
            coords = myMapApp.calcCoord(evt);
            x_initial = coords.x.toFixed(1);
            y_initial = coords.y.toFixed(1);
            initial_point = 1;
        }
        else{
            console.log('second click');
            width = Math.abs(x_final - x_initial);
            height = Math.abs(y_final - y_initial);
            x = x_initial
            if (x_final < x_initial)
                x = x_final
            y = y_initial   
            if (y_final < y_initial)
                y = y_final
            svg.setAttributeNS(null, 'viewBox', x + ' '+ y + ' ' + width + ' ' + height);
            if (rect != null)
                svg.removeChild(rect);
            initial_point = 0;
            x_final = 0;
            y_final = 0;
            x_initial = 0;
            y_initial = 0;
        }
    }
}

    function _mouseMove(evt){
    try{
        if ((cropping) && (initial_point)){
            coords = myMapApp.calcCoord(evt);
            x_final = coords.x.toFixed(1);
            y_final = coords.y.toFixed(1);
            width = Math.abs(x_final - x_initial);
            height = Math.abs(y_final - y_initial);

            console.log('1');
            x = x_initial
            if (x_final < x_initial)
                x = x_final
            y = y_initial   
            if (y_final < y_initial)
                y = y_final
            console.log('2');
            rect.setAttributeNS(null, 'fill', 'red');
            rect.setAttributeNS(null, 'stroke', 'red');
            rect.setAttributeNS(null, 'x', x);
            rect.setAttributeNS(null, 'y', y);
            rect.setAttributeNS(null, 'width', width);
            rect.setAttributeNS(null, 'height', height);
            rect.setAttributeNS(null, 'opacity', 0.5);
            console.log('3');
        }
    }catch(err){
        initial_point = 0;
        console.log(err);
        x_final = 0;
        y_final = 0;
        x_initial = 0;
        y_initial = 0;
        if (rect != null)
            svg.removeChild(rect);
    }}

'rect' 已在上面声明为公共行(var rect)。这是html5的问题,我如何管理事件?

我在这里有一个小提琴,但我有一些我不知道如何导出的库。

4

0 回答 0