WaBis

walter.bislins.ch

JSG: Vorlagen

Mit den folgenden Code-Ausschnitten können schnell Scripts mit JsGraph Elementen erstellt werden:

Um schnell eine Geafik zu erzeugen, kann der Inhalt der Seite JSG: Template verwendet werden.

Includes

#INCLUDE JsGraph.inc

NewGraph2D()

var graph = NewGraph2D( {
  Id: 'JsGraph1',
  Width: '100%',
  Height: '75%',
  DrawFunc: DrawModel,
  DeferedDrawFunc: DrawModelLabels, 
  BeforeResetFunc: function(g){},
  TextRendering: 'canvas|html',
  AutoReset: true,
  AutoClear: true,
  HighResolution: true,
  BorderWidth: 1,
  BorderColor: '',
  GraphClass: 'JsGraph',
  GraphFormat: 'VMargin',
  ScaleRef: 800,
  AutoScalePix: false,
  LimitScalePix: true,
  ScalePixInt: false,
  MinLineWidth: 0.5,
  MinTextSize: 1,
  MinMarkerSize: 1,
  DefaultAttrs: { -> SetAttrs }
} );

DrawFunc, BeforeResetFunc, AutoReset, AutoClear, HighResolution, BorderWidth, BorderColor, GraphClass, GraphFormat, ScaleRef, AutoScalePix, LimitScalePix, ScalePixInt, MinLineWidth, MinTextSize, MinMarkerSize, DefaultAttrs, SetAttrs()

DrawModel, SetViewport(), SetWindow(), Gitter und Achsen Funktionen

function DrawModel( g ) {

  g.Reset();
  g.SetAngleMeasure( AngleUnit='deg|rad' );

  g.SetViewport( X, Y, Width, Height, ScaleArgs=false, Clip=false );
  g.SetViewport( Left, Top, Right, Bottom, ScaleArgs=false, Clip=false );
  g.SetViewportRel( Left, Top, Right, Bottom, ScaleArgs=true, Clip=true );

  g.SetWindow( Xmin, Ymin, Xmax, Ymax );
  g.SetWindowWH( Xmin, Ymin, Width, Height );
  g.MapWindow( Xcenter, Ycenter, Width, Height, Align=-1|0|1 );

  g.Frame( Mode=1 );

  g.Grid( DeltaX=1, DeltaY=1, SkipZero=true, SkipLimit=false );
  g.GridX( DeltaX=1, SkipZero=true, SkipLimit=false );
  g.GridY( DeltaY=1, SkipZero=true, SkipLimit=false );

  g.Axes( PosX=0, PosY=0, ArrowSymbol='', ArrowSize=8 );
  g.AxesX( PosY=0, ArrowSymbol='', ArrowSize=8 );
  g.AxesY( PosX=0, ArrowSymbol='', ArrowSize=8 );

  g.TicsX( PosY=0, DeltaX=1, TicSizeP=3, TicSizeN=TicSizeP, SkipZero=true, SkipLimit=false );
  g.TicsY( PosX=0, DeltaY=1, TicSizeP=3, TicSizeN=PixSizeP, SkipZero=true, SkipLimit=false );

  g.TicLabelsX( PosY=0, DeltaX=1, OffsetY=-4, Scale=1, Digits=0, SkipZero=true, SkipLimit=true, Unit='' );
  g.TicLabelsY( PosX=0, DeltaY=1, OffsetX=-4, Scale=1, Digits=0, SkipZero=true, SkipLimit=true, Unit='' );

}

Reset(), SetAngleMeasure(), SetViewport(), SetViewportRel(), SetWindow(), SetWindowWH(), MapWindow()

Frame(), Grid(), GridX(), GridY(), Axes(), AxesX(), AxesY(), TicsX(), TicsY(), TicLabelsX(), TicLabelsY()

Draw-Funktionen, Pfad Funktionen

function DrawModel( g ) {

  g.PenUp();
  g.MoveTo( x, y );
  g.LineTo( x, y );

  g.NewPoly();
  var poly = g.CopyPoly();
  g.CopyPoly( poly );

  g.AddPointToPoly( x, y );
  g.DrawPoly( mode=1 );
  g.DrawPolyMarker( mode=1, mat=null );
  g.DrawPolyArrow( variant=1, lineMode=1, arrowMode=3 );

  g.Line( x1, y1, x2, y2, append=false );
  g.Polygon( xArray, yArray, mode=1 );
  g.Polygon( poly, mode=1 );

  g.PolygonArrow( xArray, yArray, variant=1, lineMode=1, arrowMode=3 );
  g.PolygonArrow( poly, variant=1, lineMode=1, arrowMode=3 );

  g.Rect( x1, y1, x2, y2, mode=1 );
  g.RectWH( x, y, w, h, mode=1 );

  g.Circle( x, y, r, mode=1, angle=0 );
  g.Arc( x, y, r, start, end, mode=1 );
  g.ArcTo( x, y, r, big=false, mode=1 );
  g.ArcPt( x1, y1, x2, y2, r, big=false, mode=1 );

  g.Ellipse( x, y, rx, ry, rot, mode=1, startAngle=0 );
  g.EllipseArc( x, y, rx, ry, rot, start, end, mode=1 ); 

  g.Text( txt, x, y );
  g.Text( txt, x, y, w, h );

  g.Marker( x, y, mode=3, [mat] );
  g.Marker( xArray, yArray, mode=3, [mat] );
  g.Marker( poly, mode=3, [mat] );

  g.OpenPath();
  g.ClosePath();
  g.Path( Mode=1, Clear=true );

  g.Clip( Clear=true );
  g.ClearPath();

}

PenUp(), MoveTo(), LineTo()

NewPoly(), CopyPoly(), AddPointToPoly(), DrawPoly(), DrawPolyArrow(), DrawPolyMarker()

Line(), Polygon(), PolygonArrow(), Rect(), RectWH(), Circle(), Arc(), ArcTo(), ArcPt(), Ellipse(), EllipseArc(), Text(), Marker()

OpenPath(), ClosePath(), Path(), Clip(), ClearPath()

Attribut Funktionen

function DrawModel( g ) {

  g.SetAlpha( 1 );
  g.SetLineJoin( 'miter|round|bevel' );
  g.SetLineCap( 'butt|round|square' );

  g.SetLineAttr( 'black', 1 );
  g.SetAreaAttr( BgColor='white', 'black', 1 );
  g.SetMarkerAttr( 'Circle', 8, 'black', BgColor='white', 1 );
  g.SetTextAttr( 'Arial', 15, 'black', 'normal|bold', 'normal|italic', 'left|center|right', 'top|middle|bottom', 0, 0 );

  var oldRendering = g.SetTextRendering( 'Html|Canvas' );
  g.SetTextRendering( oldRendering );

  g.SetColor( 'black' );
  g.SetBgColor( 'white' );
  g.SetBgColor( gradient );
  g.SetLineWidth( 1 );

  g.ClearTextAttr();
  g.SetTextClass( 'Class', ClearAttr=false );

  g.SetTextFont( 'Arial' );
  g.SetTextSize( 15 );
  g.SetTextColor( 'black' );
  g.SetLineHeight( 0 );
  g.SetFontWeight( 'normal|bold' );
  g.SetFontStyle( 'normal|italic' );
  g.SetTextAlign( 'left|center|right', 'top|middle|bottom' );
  g.SetTextHAlign( 'left|center|right' );
  g.SetTextVAlign( 'top|middle|bottom' );
  g.SetTextPadding( 0, 0 );

  g.SetMarkerSymbol( 'Circle' );
  g.SetMarkerSize( 8 );

  g.SaveAttrs();
  g.ResetAttrs();
  g.RestoreAttrs();

  var attrs = g.GetAttrs();
  g.SetAttrs( attrs );

  g.SetAttrs( {
    AngleMeasure: 'deg|rad',
    Trans: 'window|viewport|canvas',
    Alpha: 1,
    LineJoin: 'miter|round|bevel',
    LineCap: 'butt|round|square',
    :
  } );

}

SetAlpha(), SetLineJoin(), SetLineCap(), SetLineAttr(), SetAreaAttr(), SetMarkerAttr(), SetTextAttr(), SetColor(), SetBgColor(), SetLineWidth(), CreateLinearGradient(), CreateRadialGradient()

ClearTextAttr(), SetTextClass(), SetTextFont(), SetTextSize(), SetTextColor(), SetLineHeight(), SetFontWeight(), SetFontStyle(), SetTextAlign(), SetTextHAlign(), SetTextVAlign(), SetMarkerSymbol(), SetMarkerSize()

ResetAttrs(), SaveAttrs(), RestoreAttrs(), GetAttrs(), SetAttrs(), AngleMeasure, Trans, Alpha, LineJoin, LineCap

Abbildungs-Funktionen

function DrawModel( g ) {

  g.SetClipping( Range='window|viewport|canvas' );
  g.SetClipRect( X, Y, Width, Height );
  g.SetClipRect( X, Y, Width, Height, Trans='window|viewport|canvas' );

  var oldTrans = g.SelectTrans( Trans='window|viewport|canvas' );

  g.ResetTrans();
  g.TransMove( x, y );
  g.TransScale( sx, sy );
  g.TransRotate( angle );
  g.TransRotateAtPoint( x, y, angle );
  g.TransRotateAtPoint( x, y, AngleToRad(angle) );
  var mat = [[1,2,3][4,5,6]];
  g.AddTrans( mat );

  var pixelX = spanWinX * g.ScaleWinX();
  var pixelY = spanWinY * g.ScaleWinY();

  var spanWinX = pixelX / g.ScaleWinX();
  var spanWinY = pixelY / g.ScaleWinY();

}

SetClipping(), SetClipRect(), SelectTrans(), ResetTrans(), TransMove(), TransScale(), TransRotate(), TransRotateAtPoint(), AddTrans()

JsgColor

JsgColor.ToString( [ 1, 1, 1 ] )
JsgColor.ToString( [ 1, 1, 1, 1 ] )

JsgColor.HSV( 1, 1, 1 )
JsgColor.HSV( 1, 1, 1, 1 )

JsgColor.HL( 1, 1 )
JsgColor.HL( 1, 1, 1 )

JsgColor.ToString(), JsgColor.HSV(), JsgColor.HL()

Mouse Wheel Events

Füge folgenden Code auf deiner Seite ein um Mouse Wheel Events für ein Grafik-Window zu implementieren.

(function(window,document) {

    var prefix = "", _addEventListener, support;

    // detect event model
    if ( window.addEventListener ) {
        _addEventListener = "addEventListener";
    } else {
        _addEventListener = "attachEvent";
        prefix = "on";
    }

    // detect available wheel event
    support = "onwheel" in document.createElement("div") ? "wheel" : // Modern browsers support "wheel"
              document.onmousewheel !== undefined ? "mousewheel" : // Webkit and IE support at least "mousewheel"
              "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox

    window.addWheelListener = function( elem, callback, useCapture ) {
        _addWheelListener( elem, support, callback, useCapture );

        // handle MozMousePixelScroll in older Firefox
        if( support == "DOMMouseScroll" ) {
            _addWheelListener( elem, "MozMousePixelScroll", callback, useCapture );
        }
    };

    function _addWheelListener( elem, eventName, callback, useCapture ) {
        elem[ _addEventListener ]( prefix + eventName, support == "wheel" ? callback : function( originalEvent ) {
            !originalEvent && ( originalEvent = window.event );

            // create a normalized event object
            var event = {
                // keep a ref to the original event object
                originalEvent: originalEvent,
                target: originalEvent.target || originalEvent.srcElement,
                type: "wheel",
                deltaMode: originalEvent.type == "MozMousePixelScroll" ? 0 : 1,
                deltaX: 0,
                deltaY: 0,
                deltaZ: 0,
                preventDefault: function() {
                    originalEvent.preventDefault ?
                        originalEvent.preventDefault() :
                        originalEvent.returnValue = false;
                }
            };

            // calculate deltaY (and deltaX) according to the event
            if ( support == "mousewheel" ) {
                event.deltaY = - 1/40 * originalEvent.wheelDelta;
                // Webkit also support wheelDeltaX
                originalEvent.wheelDeltaX && ( event.deltaX = - 1/40 * originalEvent.wheelDeltaX );
            } else {
                event.deltaY = originalEvent.deltaY || originalEvent.detail;
            }

            // it's time to fire the callback
            return callback( event );

        }, useCapture || false );
    }

})(window,document);

Anwenung

    addWheelListener( xElement('GeoDataDisplay'),
      function( e ) {
        if (e.deltaY < 0) {
          GeoDataApp.CameraZoom *= 1.1;
        } else {
          GeoDataApp.CameraZoom /= 1.1;
        }
        GeoDataApp.Update( 'ViewPanel,CameraZoom' );
        e.preventDefault();
      }
    );

Drag, Move and Click Mouse Events

Will man Draw und Move Events in einem Grafik Fenster implementieren, muss man Click Events selbst implementieren, da die normalen Click-Handler immer zusätzlich aufgerufen werden, sobald die Maustaste losgelassen wird.

Ein Click Event sollte dann getriggert werden, wenn die Maustaste losgelassen wird und die Maus seit dem Drücken der Maustaste insgesamt nur eine sehr kleine Bewegung ausgeführt hat. In diesem Falle sollte der Drag/Move rückgängig gemacht werden und ein Click Event getriggert werden.

Der folgende Code zeigt eine mögliche Implementierung:

  OnMouseDown: function( event ) {

    event.PreventDefault();
    this.MouseIsDown = true;
    this.MouseLastPosX = event.offsetX;
    this.MouseLastPosY = event.offsetY;
    this.MouseMoveDistance = 0;

    // to cancel camera movement if we detect at click event instead a draw, 
    // save current camera angles
    this.MouseCameraAzimuth = this.CameraAzimuth;
    this.MouseCameraElevation = this.CameraElevation;
  },

  OnMouseUp: function( event ) {

    // ignore event if mouse exited window
    event.PreventDefault();
    if (!this.MouseIsDown) return;
    this.MouseIsDown = false;

    // if mouse was not moved signifantly fire click event
    if (this.MouseMoveDistance <= this.MouseMaxClickMove) {
      this.OnClick( event );
    }
  },

  OnMouseLeave: function( event ) {

    // cancel click and drag event
    this.MouseIsDown = false;
  },

  OnMouseMove: function ( event ) {

    event.PreventDefault();
    if (!this.MouseIsDown) {
      return;
    }

    var g = this.Display;
    var moveX = event.offsetX - this.MouseLastPosX;
    var moveY = event.offsetY - this.MouseLastPosY;
    this.MouseMoveDistance += Math.abs(moveX) + Math.abs(moveY);
    this.MouseLastPosX = event.offsetX;
    this.MouseLastPosY = event.offsetY;
    this.CameraAzimuth += moveX / g.VpInnerWidth * this.MouseViewRotationIncrement;
    this.CameraElevation += moveY / g.VpInnerHeight * this.MouseViewRotationIncrement;
    if (this.CameraAzimuth <= -180) this.CameraAzimuth += 360;
    if (this.CameraAzimuth > 180) this.CameraAzimuth -= 360;

    this.Update( 'ViewPanel,CameraAzimuth,CameraElevation' );
  },

  OnClick: function( event ) {
    // searches in DisplayList for the nearest point to the mouse position 
    // and selects that point if inside MouseSelectRange
    // Note: this function is called from OnMouseUp if no drag action is performed

    // searches sorted display list from nearest point to farthest point (from end to start)
    var g = this.Display;
    var minDistIx = -1;
    var minDist = 2 * this.MouseSelectRange;
    var last = this.DisplayList.Size;

    // search from farthest to nearest data point
    for (var i = 0; i < last; i++) {

      var dataPointIx = this.DisplayList.IxList[i];
      var dataPoint = GeoData[dataPointIx];

      // transform data point to canvas coordinates
      var winPos = g.TransClipPoint3D( dataPoint.Pos )
      if (winPos != null) {

        var canvasPosX = g.TransWinCnvsX( winPos[0] );
        var canvasPosY = g.TransWinCnvsY( winPos[1] );

        var diffX = event.offsetX - canvasPosX;
        var diffY = event.offsetY - canvasPosY;
        var diff = Math.sqrt( diffX*diffX + diffY*diffY );

        if (diff <= this.MouseSelectRange) {
          if (diff <= minDist) {
            minDist = diff;
            minDistIx = dataPointIx;
          }
        }
      }

    }

    // select/deselect data points

    var control = 'SelectionPanel,';

    if (event.shiftKey) {
      if (minDistIx >= 0) {
        GeoDataApp.SelPoint1 = minDistIx;
      } else {
        GeoDataApp.SelPoint1 = -1;
      }
      control += 'SelPoint1,';
    }

    if (event.ctrlKey) {
      if (minDistIx >= 0) {
        GeoDataApp.SelPoint2 = minDistIx;
      } else {
        GeoDataApp.SelPoint2 = -1;
      }
      control += 'SelPoint2,';
    }

    if (!event.shiftKey && !event.ctrlKey) {
      if (minDistIx >= 0) {
        GeoDataApp.SelRefPoint = minDistIx;
        control += 'SelRefPoint,';
      }
    }

    // if mouse has moved on a click event, reset camera position
    if (this.CameraAzimuth != this.MouseCameraAzimuth || 
        this.CameraElevation != this.MouseCameraElevation) 
    {
      this.CameraAzimuth = this.MouseCameraAzimuth;
      this.CameraElevation = this.MouseCameraElevation;
      control += 'ViewPanel,CameraAzimuth,CameraElevation,';
    }

    if (control != '') {
      this.Update( control );
    }
  },

More Page Infos / Sitemap
Created Dienstag, 2. Februar 2016
Scroll to Top of Page
Changed Sonntag, 16. Dezember 2018