Java Examples for com.google.gwt.canvas.dom.client.Context2d

The following java examples will help you to understand the usage of com.google.gwt.canvas.dom.client.Context2d. These source code samples are taken from different open source projects.

Example 1
Project: akjava_gwtlib-master  File: RectCanvasUtils.java View source code
private static void drawCircle(Canvas canvas, int x, int y, int width, int height, boolean inbox, boolean stroke) {
    int cx = x + width / 2;
    int cy = y + height / 2;
    double rad;
    if (inbox) {
        rad = width > height ? height / 2 : width / 2;
    } else {
        double longer = width > height ? width / 2 : height / 2;
        rad = Math.sqrt(Math.pow(longer, 2) * 2);
    }
    Context2d context = canvas.getContext2d();
    context.beginPath();
    canvas.getContext2d().arc(cx, cy, rad, 0, Math.PI * 2);
    context.closePath();
    if (stroke) {
        context.stroke();
    } else {
        context.fill();
    }
}
Example 2
Project: popsimple-master  File: SketchTool.java View source code
private void drawCursor() {
    Point2D pos = ElementUtils.getMousePositionRelativeToElement(this.getElement());
    final Rectangle sizeRectangle = new Rectangle(Point2D.zero, ElementUtils.getElementOffsetSize(this.getElement()));
    if ((null == pos) || (false == sizeRectangle.contains(pos))) {
        return;
    }
    Context2d cursorContext = this._cursorCanvas.getContext2d();
    if (this.isErasing()) {
        String eraserStrokeColor = "black";
        if (this.isDrawingActive()) {
            eraserStrokeColor = "red";
        }
        cursorContext.setStrokeStyle(eraserStrokeColor);
        cursorContext.setFillStyle("rgba(255,255,255,0.5)");
        cursorContext.setLineWidth(1);
        cursorContext.beginPath();
        cursorContext.rect(pos.getX() - this.data.sketchOptions.eraserWidth / 2, pos.getY() - this.data.sketchOptions.eraserWidth / 2, this.data.sketchOptions.eraserWidth, this.data.sketchOptions.eraserWidth);
        cursorContext.closePath();
        if (this.isDrawingActive()) {
            cursorContext.fill();
        }
        cursorContext.stroke();
    } else {
        cursorContext.setStrokeStyle("transparent");
        cursorContext.setFillStyle(this.data.sketchOptions.penColor);
        cursorContext.beginPath();
        cursorContext.arc(pos.getX(), pos.getY(), this.data.sketchOptions.penWidth / 2, 0, Math.PI * 2);
        cursorContext.closePath();
        cursorContext.fill();
    }
}
Example 3
Project: geogebra-master  File: GgbAPIW.java View source code
private static String convertImgToPng(MyImageW img) {
    String url;
    Canvas cv = Canvas.createIfSupported();
    cv.setCoordinateSpaceWidth(img.getWidth());
    cv.setCoordinateSpaceHeight(img.getHeight());
    Context2d c2d = cv.getContext2d();
    c2d.drawImage(img.getImage(), 0, 0);
    url = cv.toDataUrl("image/png");
    // else
    return url;
}
Example 4
Project: mgwt.showcase-master  File: Test.java View source code
public void bla() {
    Context2d ctx = Canvas.createIfSupported().getContext2d();
    // Draw a rectangle with default settings
    ctx.fillRect(0, 0, 150, 150);
    // Save the default state
    ctx.save();
    // Make changes to the settings
    ctx.setFillStyle("#09F");
    // Draw a rectangle with new settings
    ctx.fillRect(15, 15, 120, 120);
    // Save the current state
    ctx.save();
    // Make changes to the settings
    ctx.setFillStyle("#FFF");
    ctx.setGlobalAlpha(0.5);
    // Draw a rectangle with new settings
    ctx.fillRect(30, 30, 90, 90);
    // Restore previous state
    ctx.restore();
    // Draw a rectangle with restored settings
    ctx.fillRect(45, 45, 60, 60);
    // Restore original state
    ctx.restore();
    // Draw a rectangle with restored settings
    ctx.fillRect(60, 60, 30, 30);
}
Example 5
Project: Zong-master  File: GwtCanvasLayoutRenderer.java View source code
/**
	 * Paints the given page of the given {@link Layout} at the given zoom level
	 * into the given {@link CanvasElement}, which is resized to include the whole page.
	 * The size in pixel is also returned.
	 */
public static Size2i paintToCanvas(Layout layout, int pageIndex, float zoom, com.google.gwt.canvas.client.Canvas canvas) {
    Context2d context = canvas.getContext2d();
    //compute size
    Page page = layout.getPages().get(pageIndex);
    Size2f pageSize = page.getFormat().getSize();
    int width = Units.mmToPxInt(pageSize.width, zoom);
    int height = Units.mmToPxInt(pageSize.height, zoom);
    //resize canvas and coordinate space
    canvas.setWidth(width + "px");
    canvas.setHeight(height + "px");
    //double resolution: smoother
    int coordSpaceFactor = 2;
    canvas.setCoordinateSpaceWidth(width * coordSpaceFactor);
    canvas.setCoordinateSpaceHeight(height * coordSpaceFactor);
    context.scale(coordSpaceFactor, coordSpaceFactor);
    //white page
    context.setFillStyle("white");
    context.fillRect(0, 0, width, height);
    //paint layout
    LayoutRenderer.paintToCanvas(layout, pageIndex, zoom, origin, new GwtCanvas(context, CanvasFormat.Raster, CanvasDecoration.Interactive, CanvasIntegrity.Perfect));
    return new Size2i(width, height);
}
Example 6
Project: vtm-master  File: GwtCanvas.java View source code
@Override
public void drawText(String string, float x, float y, Paint fill, Paint stroke) {
    if (bitmap == null) {
        //log.debug("no bitmap set");
        return;
    }
    GwtPaint p = (GwtPaint) fill;
    if (p.stroke && GwtGdxGraphics.NO_STROKE_TEXT)
        return;
    Context2d ctx = bitmap.pixmap.getContext();
    ctx.setFont(p.font);
    if (p.stroke) {
        ctx.setLineWidth(p.strokeWidth);
        ctx.setStrokeStyle(p.color);
        ctx.strokeText(string, (int) (x + 1), (int) (y + 1));
    } else {
        ctx.setFillStyle(p.color);
        ctx.fillText(string, (int) (x + 1), (int) (y + 1));
    }
}
Example 7
Project: rstudio-master  File: FontDetector.java View source code
public static boolean isFontSupported(String fontName) {
    SimplePanel panel = null;
    try {
        // default font name as a reference point
        final String defaultFontName = "Arial";
        if (defaultFontName.equals(fontName))
            return true;
        // make sure canvas is supported
        if (!Canvas.isSupported())
            return false;
        // add a temporary div to the dom
        panel = new SimplePanel();
        panel.setHeight("200px");
        panel.getElement().getStyle().setVisibility(Visibility.HIDDEN);
        panel.getElement().getStyle().setOverflow(Overflow.SCROLL);
        RootPanel.get().add(panel, -2000, -2000);
        // add a canvas element to the div and get the 2d drawing context
        final Canvas canvas = Canvas.createIfSupported();
        canvas.setWidth("512px");
        canvas.setHeight("64px");
        canvas.getElement().getStyle().setLeft(400, Unit.PX);
        canvas.getElement().getStyle().setBackgroundColor("#ffe");
        panel.add(canvas);
        final Context2d ctx = canvas.getContext2d();
        ctx.setFillStyle("#000000");
        // closure to generate a hash for a font
        class HashGenerator {

            public String getHash(String fontName) {
                ctx.setFont("57px " + fontName + ", " + defaultFontName);
                int width = canvas.getOffsetWidth();
                int height = canvas.getOffsetHeight();
                ctx.clearRect(0, 0, width, height);
                ctx.fillText("TheQuickBrownFox", 2, 50);
                return canvas.toDataUrl();
            }
        }
        ;
        // get hashes and compare them
        HashGenerator hashGenerator = new HashGenerator();
        String defaultHash = hashGenerator.getHash(defaultFontName);
        String fontHash = hashGenerator.getHash(fontName);
        return !defaultHash.equals(fontHash);
    } catch (Exception ex) {
        Debug.log(ex.toString());
        return false;
    } finally {
        if (panel != null)
            RootPanel.get().remove(panel);
    }
}
Example 8
Project: GWTChromeCast-master  File: TicTacToeApp.java View source code
/**
	 * Initializes the receiver application and game objects, and starts the
	 * receiver.
	 */
@Override
public void onModuleLoad() {
    Canvas canvas = Canvas.createIfSupported();
    canvas.getCanvasElement().setId("board");
    canvas.addStyleName("canvas");
    RootPanel.get().add(canvas);
    Context2d context = canvas.getContext2d();
    context.getCanvas().setWidth(Window.getClientWidth());
    context.getCanvas().setHeight(Window.getClientHeight());
    Board mBoard = new Board(context);
    String appId = "ce2ad55e-2181-44bb-b5e7-9e65e0510d86";
    ArrayList<String> protocol = new ArrayList<String>(1);
    protocol.add(PROTOCOL);
    Receiver chromecastApp = Receiver.create(appId, protocol, JavaScriptObject.createObject(), 5);
    mBoard.clear();
    mBoard.drawGrid();
    TicTacToe gameEngine = new TicTacToe(mBoard);
    gameEngine.mChannelHandler.addChannelFactory(chromecastApp.createChannelFactory(PROTOCOL));
    chromecastApp.start();
}
Example 9
Project: LGA-master  File: GWTImage.java View source code
public static ImageData scaleImage(ImageElement image, float scaleToRatioh, float scaleToRatiow) {
    Canvas canvasTmp = Canvas.createIfSupported();
    Context2d context = canvasTmp.getContext2d();
    float ch = (image.getHeight() * scaleToRatioh);
    float cw = (image.getWidth() * scaleToRatiow);
    canvasTmp.setCoordinateSpaceHeight((int) ch);
    canvasTmp.setCoordinateSpaceWidth((int) cw);
    float sx = 0;
    float sy = 0;
    float sw = image.getWidth();
    float sh = image.getHeight();
    float dx = 0;
    float dy = 0;
    float dw = image.getWidth();
    float dh = image.getHeight();
    context.scale(scaleToRatioh, scaleToRatiow);
    context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
    float w = dw * scaleToRatioh;
    float h = dh * scaleToRatiow;
    ImageData imageData = context.getImageData(0, 0, w, h);
    return imageData;
}
Example 10
Project: LGame-master  File: GWTImage.java View source code
public static ImageData scaleImage(ImageElement image, float scaleToRatioh, float scaleToRatiow) {
    Canvas canvasTmp = Canvas.createIfSupported();
    Context2d context = canvasTmp.getContext2d();
    float ch = (image.getHeight() * scaleToRatioh);
    float cw = (image.getWidth() * scaleToRatiow);
    canvasTmp.setCoordinateSpaceHeight((int) ch);
    canvasTmp.setCoordinateSpaceWidth((int) cw);
    float sx = 0;
    float sy = 0;
    float sw = image.getWidth();
    float sh = image.getHeight();
    float dx = 0;
    float dy = 0;
    float dw = image.getWidth();
    float dh = image.getHeight();
    context.scale(scaleToRatioh, scaleToRatiow);
    context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
    float w = dw * scaleToRatioh;
    float h = dh * scaleToRatiow;
    ImageData imageData = context.getImageData(0, 0, w, h);
    return imageData;
}
Example 11
Project: playn-master  File: HtmlGraphics.java View source code
HtmlFontMetrics getFontMetrics(HtmlFont font) {
    HtmlFontMetrics metrics = fontMetrics.get(font);
    if (metrics == null) {
        // TODO: when Context2d.measureText some day returns a height, nix this hackery
        measureElement.getStyle().setFontSize(font.size(), Unit.PX);
        measureElement.getStyle().setFontWeight(Style.FontWeight.NORMAL);
        measureElement.getStyle().setFontStyle(Style.FontStyle.NORMAL);
        measureElement.getStyle().setProperty("fontFamily", font.name());
        measureElement.setInnerText(HEIGHT_TEXT);
        switch(font.style()) {
            case BOLD:
                measureElement.getStyle().setFontWeight(Style.FontWeight.BOLD);
                break;
            case ITALIC:
                measureElement.getStyle().setFontStyle(Style.FontStyle.ITALIC);
                break;
            case BOLD_ITALIC:
                measureElement.getStyle().setFontWeight(Style.FontWeight.BOLD);
                measureElement.getStyle().setFontStyle(Style.FontStyle.ITALIC);
                break;
            default:
                // nada
                break;
        }
        float height = measureElement.getOffsetHeight();
        measureElement.setInnerText(EMWIDTH_TEXT);
        float emwidth = measureElement.getOffsetWidth();
        metrics = new HtmlFontMetrics(font, height, emwidth);
        fontMetrics.put(font, metrics);
    }
    return metrics;
}
Example 12
Project: umlet-master  File: DrawHandlerGwt.java View source code
/**
	 * based on http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas/2173084#2173084
	 */
private static void drawEllipseHelper(Context2d ctx, boolean drawOuterLine, double x, double y, double w, double h) {
    double kappa = .5522848f;
    // control point offset horizontal
    double ox = w / 2 * kappa;
    // control point offset vertical
    double oy = h / 2 * kappa;
    // x-end
    double xe = x + w;
    // y-end
    double ye = y + h;
    // x-middle
    double xm = x + w / 2;
    // y-middle
    double ym = y + h / 2;
    ctx.beginPath();
    ctx.moveTo(x, ym);
    ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
    ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
    ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
    ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
    ctx.fill();
    if (drawOuterLine) {
        ctx.stroke();
    }
}
Example 13
Project: geomajas-project-client-gwt2-master  File: CanvasImageElement.java View source code
@Override
public void paint(Canvas canvas, Matrix matrix) {
    /*
		* paint image on canvas based on the original and with the transformations of the matrix.
		* */
    Context2d context2d = canvas.getContext2d();
    context2d.save();
    boolean xReversal = matrix.getXx() < 0;
    boolean yReversal = matrix.getYy() < 0;
    context2d.scale(xReversal ? -1 : 1, yReversal ? -1 : 1);
    double xValue = xReversal ? box.getMaxX() * -1 : box.getX();
    double yValue = yReversal ? box.getMaxY() * -1 : box.getY();
    context2d.drawImage(hiddenImageCanvas.getCanvasElement(), xValue, yValue, box.getWidth(), box.getHeight());
    context2d.restore();
}
Example 14
Project: Flax-HTML5-Game-Engine-master  File: FMap.java View source code
/**
	 * This calls all the draw methods of the entities in the FMap, the tiles and checks weather they are on-screen and
	 * if they are they are then drawn to the screen.
	 * @param canvas 
	 * @param cam2 
	 */
public void draw(final FCamera cam, final Canvas drawingSpace, //Ok this shouldn't be here, need to have a thing about how going to do update and drawing.
final double deltaTime) //No piont looping though all the elements twice for update and draw, so why not at same time, but anyway need to sleep on it
{
    /**
			 * The below calucates and objects referencing is all done outside the loops to speed up the drawing
			 * TODO Ciaran - at some piont slim down these varibles. Wont save much but could be done some time
			 */
    final double camX = cam.getX();
    final double camY = cam.getY();
    final double camXWidth = camX + cam.getWidth();
    final double camYHeight = camY + cam.getHeight();
    //plus one gives a border tile
    int camXRelative = (int) (camX / tileSize);
    int camYRelative = (int) (camY / tileSize);
    final int camXAndWidth = (int) ((camXRelative) + cam.getWidth() / tileSize) + 1;
    final int camYAndHeight = (int) ((camYRelative) + cam.getHeight() / tileSize) + 1;
    final int camXRelativeCopy = camXRelative;
    final int camYRelativeCopy = camYRelative;
    final int camXRelativeCopyScaled = camXRelativeCopy * tileSize;
    final int camYRelativeCopyScaled = camYRelativeCopy * tileSize;
    final int totalTiles = tiles.size();
    final Context2d ctx = drawingSpace.getContext2d();
    FTile t = null;
    /**
			 * currentYValue varibles is here to save on a multication and a subtraction every row item ( x corrdinate or coloum). 
			 */
    int currentYValue = 0;
    /**
			 * Again like the currentYValue this varible exists to remove a multication  for every row item
			 */
    int currentYindexValue = 0;
    ctx.save();
    ctx.translate(cam.getInterpolation().x, cam.getInterpolation().y);
    // all in tiles - relative
    while (camYRelative <= camYAndHeight) {
        /**
				 * -1 to allow for the panning, read large comment below
				 */
        // get next Y value
        currentYValue = ((camYRelative - 1) * tileSize - camYRelativeCopyScaled);
        // get the next Y index value
        currentYindexValue = (camYRelative) * width;
        // in number of tiles - relatived
        while (camXRelative <= camXAndWidth) {
            if (camXRelative + currentYindexValue >= totalTiles)
                break;
            t = tiles.get(camXRelative + currentYindexValue);
            /**
					 * below is the call for the image to be drawn, note the -1 on the camXRelative, this is to facilate the panning.
					 * Basically it makes the map render with -1 positon and thus there will always a border tile colum, so when the camera is panning
					 * you don't notice anything wiered. 
					 * 
					 * I'm sure there is a better way to do this, tho it will do for the mo
					 * 
					 */
            ctx.drawImage(tileSheetImage, t.getTextureX(), t.getTextureY(), tileSize, tileSize, ((camXRelative - 1) * tileSize - camXRelativeCopyScaled), currentYValue, tileSize, tileSize);
            camXRelative++;
        }
        // rest the X to intial
        camXRelative = camXRelativeCopy;
        camYRelative++;
    }
    ctx.restore();
    for (FObject temp : objects) {
        //check if the eneity can be seen on screen before drawing
        if (temp.getX() >= camX - tileSize && temp.getX() <= camXWidth && temp.getY() >= camY - tileSize && temp.getY() <= camYHeight) {
            if (deltaTime != -1)
                temp.update(deltaTime);
            temp.draw(drawingSpace);
        }
    }
    for (FEntity temp : entities) {
        //check if the eneity can be seen on screen before drawing
        if (temp.getX() >= camX - temp.getWidth() && temp.getX() <= camXWidth && temp.getY() >= camY - temp.getHeight() && temp.getY() <= camYHeight) {
            if (deltaTime != -1)
                temp.update(deltaTime);
            temp.draw(drawingSpace);
        }
    }
}
Example 15
Project: mgwt-master  File: ImageConverter.java View source code
public ImageResource convert(ImageResource resource, String color) {
    if (color == null) {
        throw new IllegalArgumentException();
    }
    if (!color.startsWith("#")) {
        throw new IllegalArgumentException();
    }
    int hexColor = Integer.parseInt(color.substring(1), 16);
    int red = hexColor >> 16 & 0xFF;
    int green = hexColor >> 8 & 0xFF;
    int blue = hexColor & 0xFF;
    int height = resource.getHeight();
    int width = resource.getWidth();
    ImageElement imageElement = loadImage(resource.getSafeUri().asString(), width, height);
    Canvas canvas = Canvas.createIfSupported();
    canvas.getElement().setPropertyInt("height", height);
    canvas.getElement().setPropertyInt("width", width);
    Context2d context = canvas.getContext2d();
    context.drawImage(imageElement, 0, 0);
    ImageData imageData = context.getImageData(0, 0, width, height);
    CanvasPixelArray canvasPixelArray = imageData.getData();
    for (int i = 0; i < canvasPixelArray.getLength(); i += 4) {
        canvasPixelArray.set(i, red);
        canvasPixelArray.set(i + 1, green);
        canvasPixelArray.set(i + 2, blue);
        canvasPixelArray.set(i + 3, canvasPixelArray.get(i + 3));
    }
    context.putImageData(imageData, 0, 0);
    return new ConvertedImageResource(canvas.toDataUrl("image/png"), resource.getWidth(), resource.getHeight());
}
Example 16
Project: prima-gwt-lib-master  File: EditOutlineTool.java View source code
@Override
public void render(PageRenderer renderer) {
    if (!isEnabled())
        return;
    Context2d context = renderer.getContext();
    //Draw the selected outline in red
    RenderStyle style = new RenderStyle("rgb(255,0,0)", "transparent", 1.0);
    PolygonRendererHelper.drawPolygon(context, polygon, style, renderer.getZoomFactor(), true, false);
    //Delete mode
    if (deletePointsMode) {
        if (currentPolygonPoint != null) {
            context.setFillStyle(DELETE_POINT_FILL_COLOR);
            context.setStrokeStyle(DELETE_POINT_LINE_COLOR);
            context.setLineWidth(1.0 / renderer.getZoomFactor());
            //Cross
            context.beginPath();
            int size = (int) (3.0 / view.getZoomFactor());
            context.moveTo(currentPolygonPoint.x - 2 * size, currentPolygonPoint.y - 3 * size);
            context.lineTo(currentPolygonPoint.x, currentPolygonPoint.y - size);
            context.lineTo(currentPolygonPoint.x + 2 * size, currentPolygonPoint.y - 3 * size);
            context.lineTo(currentPolygonPoint.x + 3 * size, currentPolygonPoint.y - 2 * size);
            context.lineTo(currentPolygonPoint.x + size, currentPolygonPoint.y);
            context.lineTo(currentPolygonPoint.x + 3 * size, currentPolygonPoint.y + 2 * size);
            context.lineTo(currentPolygonPoint.x + 2 * size, currentPolygonPoint.y + 3 * size);
            context.lineTo(currentPolygonPoint.x, currentPolygonPoint.y + size);
            context.lineTo(currentPolygonPoint.x - 2 * size, currentPolygonPoint.y + 3 * size);
            context.lineTo(currentPolygonPoint.x - 3 * size, currentPolygonPoint.y + 2 * size);
            context.lineTo(currentPolygonPoint.x - size, currentPolygonPoint.y);
            context.lineTo(currentPolygonPoint.x - 3 * size, currentPolygonPoint.y - 2 * size);
            context.lineTo(currentPolygonPoint.x - 2 * size, currentPolygonPoint.y - 3 * size);
            context.fill();
            context.stroke();
        }
    } else //Add or move mode
    {
        //Move point
        if (currentPolygonPoint != null) {
            context.setFillStyle(POINT_HIGHLIGHT_FILL_COLOR);
            context.setStrokeStyle(POINT_HIGHLIGHT_LINE_COLOR);
            context.setLineWidth(1.0 / renderer.getZoomFactor());
            int size = (int) (3.0 / view.getZoomFactor());
            //Rect in centre
            context.beginPath();
            context.rect(currentPolygonPoint.x - size, currentPolygonPoint.y - size, 2 * size + 1, 2 * size + 1);
            context.fill();
            context.stroke();
            //Arrows
            // Left
            context.beginPath();
            context.moveTo(currentPolygonPoint.x - 2 * size, currentPolygonPoint.y + size);
            context.lineTo(currentPolygonPoint.x - 2 * size, currentPolygonPoint.y - size);
            context.lineTo(currentPolygonPoint.x - 3 * size, currentPolygonPoint.y);
            context.lineTo(currentPolygonPoint.x - 2 * size, currentPolygonPoint.y + size);
            context.fill();
            context.stroke();
            // Right
            context.beginPath();
            context.moveTo(currentPolygonPoint.x + 2 * size, currentPolygonPoint.y + size);
            context.lineTo(currentPolygonPoint.x + 2 * size, currentPolygonPoint.y - size);
            context.lineTo(currentPolygonPoint.x + 3 * size, currentPolygonPoint.y);
            context.lineTo(currentPolygonPoint.x + 2 * size, currentPolygonPoint.y + size);
            context.fill();
            context.stroke();
            // Top
            context.beginPath();
            context.moveTo(currentPolygonPoint.x + size, currentPolygonPoint.y - 2 * size);
            context.lineTo(currentPolygonPoint.x - size, currentPolygonPoint.y - 2 * size);
            context.lineTo(currentPolygonPoint.x, currentPolygonPoint.y - 3 * size);
            context.lineTo(currentPolygonPoint.x + size, currentPolygonPoint.y - 2 * size);
            context.fill();
            context.stroke();
            // Bottom
            context.beginPath();
            context.moveTo(currentPolygonPoint.x + size, currentPolygonPoint.y + 2 * size);
            context.lineTo(currentPolygonPoint.x - size, currentPolygonPoint.y + 2 * size);
            context.lineTo(currentPolygonPoint.x, currentPolygonPoint.y + 3 * size);
            context.lineTo(currentPolygonPoint.x + size, currentPolygonPoint.y + 2 * size);
            context.fill();
            context.stroke();
        }
        //Add point
        if (newPolygonPointCandidate != null) {
            context.setFillStyle(POINT_HIGHLIGHT_FILL_COLOR);
            context.setStrokeStyle(POINT_HIGHLIGHT_LINE_COLOR);
            context.setLineWidth(1.0 / renderer.getZoomFactor());
            //Plus sign
            context.beginPath();
            int size = (int) (3.0 / view.getZoomFactor());
            context.moveTo(newPolygonPointCandidate.x - size, newPolygonPointCandidate.y - 3 * size);
            context.lineTo(newPolygonPointCandidate.x + size, newPolygonPointCandidate.y - 3 * size);
            context.lineTo(newPolygonPointCandidate.x + size, newPolygonPointCandidate.y - size);
            context.lineTo(newPolygonPointCandidate.x + 3 * size, newPolygonPointCandidate.y - size);
            context.lineTo(newPolygonPointCandidate.x + 3 * size, newPolygonPointCandidate.y + size);
            context.lineTo(newPolygonPointCandidate.x + size, newPolygonPointCandidate.y + size);
            context.lineTo(newPolygonPointCandidate.x + size, newPolygonPointCandidate.y + 3 * size);
            context.lineTo(newPolygonPointCandidate.x - size, newPolygonPointCandidate.y + 3 * size);
            context.lineTo(newPolygonPointCandidate.x - size, newPolygonPointCandidate.y + size);
            context.lineTo(newPolygonPointCandidate.x - 3 * size, newPolygonPointCandidate.y + size);
            context.lineTo(newPolygonPointCandidate.x - 3 * size, newPolygonPointCandidate.y - size);
            context.lineTo(newPolygonPointCandidate.x - size, newPolygonPointCandidate.y - size);
            context.lineTo(newPolygonPointCandidate.x - size, newPolygonPointCandidate.y - 3 * size);
            context.fill();
            context.stroke();
        }
    }
}
Example 17
Project: skWiki-master  File: DashedLineRenderer.java View source code
/**
	 * Draw a dashed line from (fromX, fromY) to (toX, toY).
	 * 
	 * @param context
	 * @param fromX x-coordinate of the starting point
	 * @param fromY y-coordinate of the starting point
	 * @param toX x-coordinate of the ending point
	 * @param toY y-coordinate of the ending point
	 * @param dashLength length of the dash
	 * @param gapLength length of the gap in between dashes
	 */
public static void drawDashedLine(Context2d context, double fromX, double fromY, double toX, double toY, double dashLength, double gapLength) {
    DashedLineHelper checkX = GreaterThanHelper.instance;
    DashedLineHelper checkY = GreaterThanHelper.instance;
    if (fromY - toY > 0) {
        checkY = LessThanHelper.instance;
    }
    if (fromX - toX > 0) {
        checkX = LessThanHelper.instance;
    }
    context.moveTo(fromX, fromY);
    double offsetX = fromX;
    double offsetY = fromY;
    boolean dash = true;
    double ang = Math.atan2(toY - fromY, toX - fromX);
    while (!(checkX.isThereYet(offsetX, toX) && checkY.isThereYet(offsetY, toY))) {
        double len = (dash) ? dashLength : gapLength;
        offsetX = checkX.getCap(toX, offsetX + (Math.cos(ang) * len));
        offsetY = checkY.getCap(toY, offsetY + (Math.sin(ang) * len));
        if (dash) {
            context.lineTo(offsetX, offsetY);
        } else {
            context.moveTo(offsetX, offsetY);
        }
        dash = !dash;
    }
}
Example 18
Project: google-web-toolkit-svnmirror-master  File: CanvasTest.java View source code
public void testHeightAndWidth() {
    if (canvas1 == null) {
        // don't continue if not supported
        return;
    }
    canvas1.setHeight("40px");
    canvas1.setWidth("60px");
    assertEquals(40, canvas1.getOffsetHeight());
    assertEquals(60, canvas1.getOffsetWidth());
    // resize
    canvas1.setHeight("41px");
    canvas1.setWidth("61px");
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
    // add 2d context, resize internal size, should have no effect
    Context2d context = canvas1.getContext2d();
    canvas1.setCoordinateSpaceHeight(140);
    canvas1.setCoordinateSpaceWidth(160);
    context.fillRect(2, 2, 300, 300);
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
}
Example 19
Project: gwt-master  File: CanvasTest.java View source code
public void testHeightAndWidth() {
    if (canvas1 == null) {
        // don't continue if not supported
        return;
    }
    canvas1.setHeight("40px");
    canvas1.setWidth("60px");
    assertEquals(40, canvas1.getOffsetHeight());
    assertEquals(60, canvas1.getOffsetWidth());
    // resize
    canvas1.setHeight("41px");
    canvas1.setWidth("61px");
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
    // add 2d context, resize internal size, should have no effect
    Context2d context = canvas1.getContext2d();
    canvas1.setCoordinateSpaceHeight(140);
    canvas1.setCoordinateSpaceWidth(160);
    context.fillRect(2, 2, 300, 300);
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
}
Example 20
Project: gwt-sandbox-master  File: CanvasTest.java View source code
public void testHeightAndWidth() {
    if (canvas1 == null) {
        // don't continue if not supported
        return;
    }
    canvas1.setHeight("40px");
    canvas1.setWidth("60px");
    assertEquals(40, canvas1.getOffsetHeight());
    assertEquals(60, canvas1.getOffsetWidth());
    // resize
    canvas1.setHeight("41px");
    canvas1.setWidth("61px");
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
    // add 2d context, resize internal size, should have no effect
    Context2d context = canvas1.getContext2d();
    canvas1.setCoordinateSpaceHeight(140);
    canvas1.setCoordinateSpaceWidth(160);
    context.fillRect(2, 2, 300, 300);
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
}
Example 21
Project: gwt.svn-master  File: CanvasTest.java View source code
public void testHeightAndWidth() {
    if (canvas1 == null) {
        // don't continue if not supported
        return;
    }
    canvas1.setHeight("40px");
    canvas1.setWidth("60px");
    assertEquals(40, canvas1.getOffsetHeight());
    assertEquals(60, canvas1.getOffsetWidth());
    // resize
    canvas1.setHeight("41px");
    canvas1.setWidth("61px");
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
    // add 2d context, resize internal size, should have no effect
    Context2d context = canvas1.getContext2d();
    canvas1.setCoordinateSpaceHeight(140);
    canvas1.setCoordinateSpaceWidth(160);
    context.fillRect(2, 2, 300, 300);
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
}
Example 22
Project: scalagwt-gwt-master  File: CanvasTest.java View source code
public void testHeightAndWidth() {
    if (canvas1 == null) {
        // don't continue if not supported
        return;
    }
    canvas1.setHeight("40px");
    canvas1.setWidth("60px");
    assertEquals(40, canvas1.getOffsetHeight());
    assertEquals(60, canvas1.getOffsetWidth());
    // resize
    canvas1.setHeight("41px");
    canvas1.setWidth("61px");
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
    // add 2d context, resize internal size, should have no effect
    Context2d context = canvas1.getContext2d();
    canvas1.setCoordinateSpaceHeight(140);
    canvas1.setCoordinateSpaceWidth(160);
    context.fillRect(2, 2, 300, 300);
    assertEquals(41, canvas1.getOffsetHeight());
    assertEquals(61, canvas1.getOffsetWidth());
}
Example 23
Project: beboj-master  File: DrawWay.java View source code
@Override
public void paint(Graphics2D g, MapView mv, Bounds bbox) {
    Context2d c = ((CanvasGraphics2D) g).getContext2d();
    // don't draw line if we don't know where to
    if (lastMousePos == null)
        return;
    // don't draw line if mouse is outside window
    if (!Main.map.mapView.view.getBounds().contains(lastMousePos))
        return;
    Point p1 = mv.getPoint(lastNode);
    Point p2 = lastMousePos;
    c.setStrokeStyle("#ffff00");
    c.beginPath();
    c.moveTo(p1.x, p1.y);
    c.lineTo(p2.x, p2.y);
    c.stroke();
}
Example 24
Project: forplay-master  File: HtmlPath.java View source code
void replay(Context2d ctx) {
    ctx.beginPath();
    int len = list.length(), i = 0;
    double x = 0, y = 0;
    while (i < len) {
        switch((int) list.get(i++)) {
            case CMD_MOVE:
                {
                    x = list.get(i++);
                    y = list.get(i++);
                    ctx.moveTo(x, y);
                    break;
                }
            case CMD_LINE:
                {
                    x = list.get(i++);
                    y = list.get(i++);
                    ctx.lineTo(x, y);
                    break;
                }
            case CMD_QUAD:
                {
                    double cpx = list.get(i++);
                    double cpy = list.get(i++);
                    x = list.get(i++);
                    y = list.get(i++);
                    ctx.quadraticCurveTo(cpx, cpy, x, y);
                    break;
                }
            case CMD_ARC:
                {
                    double curX = x, curY = 0;
                    double radius = list.get(i++);
                    x = list.get(i++);
                    y = list.get(i++);
                    ctx.arcTo(curX, curY, x, y, radius);
                    break;
                }
            case CMD_CLOSE:
                {
                    ctx.closePath();
                    break;
                }
            default:
                throw new AssertionError("Corrupt command list");
        }
    }
}
Example 25
Project: jetpad-projectional-master  File: TextMetricsCalculator.java View source code
private static int measureHeight(Font font, String text) {
    Canvas canvas = canvas();
    Context2d ctx = canvas.getContext2d();
    ctx.setFont(getFontString(font));
    ctx.setFillStyle("rgb(255, 0, 0)");
    int width = (int) ctx.measureText(text).getWidth();
    int canvasHeight = font.getSize() * 2;
    canvas.setHeight(canvasHeight + "px");
    canvas.setHeight(font.getSize() * 2 + "px");
    canvas.setWidth(width + "px");
    ctx.fillText(text, 0, font.getSize());
    ImageData data = ctx.getImageData(0, 0, width, canvasHeight);
    int firstY = canvasHeight - 1;
    int lastY = 0;
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < canvasHeight; y++) {
            int red = data.getRedAt(x, y);
            if (red != 0) {
                if (firstY > y) {
                    firstY = y;
                }
                if (lastY < y) {
                    lastY = y;
                }
            }
        }
    }
    return lastY - firstY;
}
Example 26
Project: Peergos-master  File: PieChart.java View source code
/**
   * Redraw the pie chart.
   */
public void redraw() {
    if (!isAttached()) {
        return;
    }
    // Get the dimensions of the chart.
    int width = canvas.getCoordinateSpaceWidth();
    int height = canvas.getCoordinateSpaceHeight();
    double radius = Math.min(width, height) / 2.0;
    double cx = width / 2.0;
    double cy = height / 2.0;
    // Clear the context.
    Context2d context = canvas.getContext2d();
    context.clearRect(0, 0, width, height);
    // Get the total weight of all slices.
    double totalWeight = 0;
    for (Slice slice : slices) {
        totalWeight += slice.weight;
    }
    // Draw the slices.
    double startAngle = -0.5 * Math.PI;
    for (Slice slice : slices) {
        double weight = slice.weight / totalWeight;
        double endAngle = startAngle + (weight * RADIANS_IN_CIRCLE);
        context.setFillStyle(slice.fill);
        context.beginPath();
        context.moveTo(cx, cy);
        context.arc(cx, cy, radius, startAngle, endAngle);
        context.fill();
        startAngle = endAngle;
    }
}
Example 27
Project: teavm-master  File: BenchmarkStarter.java View source code
private void render() {
    Context2d context = canvas.getContext2d();
    context.setFillStyle("white");
    context.setStrokeStyle("grey");
    context.fillRect(0, 0, 600, 600);
    context.save();
    context.translate(0, 600);
    context.scale(1, -1);
    context.scale(100, 100);
    context.setLineWidth(0.01);
    for (Body body = scene.getWorld().getBodyList(); body != null; body = body.getNext()) {
        Vec2 center = body.getPosition();
        context.save();
        context.translate(center.x, center.y);
        context.rotate(body.getAngle());
        for (Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) {
            Shape shape = fixture.getShape();
            if (shape.getType() == ShapeType.CIRCLE) {
                CircleShape circle = (CircleShape) shape;
                context.beginPath();
                context.arc(circle.m_p.x, circle.m_p.y, circle.getRadius(), 0, Math.PI * 2, true);
                context.closePath();
                context.stroke();
            } else if (shape.getType() == ShapeType.POLYGON) {
                PolygonShape poly = (PolygonShape) shape;
                Vec2[] vertices = poly.getVertices();
                context.beginPath();
                context.moveTo(vertices[0].x, vertices[0].y);
                for (int i = 1; i < poly.getVertexCount(); ++i) {
                    context.lineTo(vertices[i].x, vertices[i].y);
                }
                context.closePath();
                context.stroke();
            }
        }
        context.restore();
    }
    context.restore();
}
Example 28
Project: TGAReader-master  File: TexturedCube.java View source code
Canvas createImageCanvas(int[] pixels, int width, int height) {
    Canvas canvas = Canvas.createIfSupported();
    canvas.setCoordinateSpaceWidth(width);
    canvas.setCoordinateSpaceHeight(height);
    Context2d context = canvas.getContext2d();
    ImageData data = context.createImageData(width, height);
    CanvasPixelArray array = data.getData();
    for (int i = 0; i < width * height; i++) {
        array.set(4 * i + 0, pixels[i] & 0xFF);
        array.set(4 * i + 1, (pixels[i] >> 8) & 0xFF);
        array.set(4 * i + 2, (pixels[i] >> 16) & 0xFF);
        array.set(4 * i + 3, (pixels[i] >> 24) & 0xFF);
    }
    context.putImageData(data, 0, 0);
    return canvas;
}
Example 29
Project: OpenTripPlanner-client-gwt-master  File: ItineraryDetailsWidget.java View source code
/**
	 * Build the background image for the widget, according to the mode. Draw
	 * the mode image and a solid line below it with the route color (if in
	 * transit mode) or a dotted line (if in road mode). Set the
	 * background-image to the generated image for the given widget.
	 */
public static void styleComponentWithMode(final Widget widget, TransportMode mode, String color) {
    PlannerResources resources = PlannerResources.INSTANCE;
    ImageResource baseImage = null;
    boolean road = false;
    switch(mode) {
        case WALK:
            road = true;
            color = "#666666";
            baseImage = resources.modeWalkPng();
            break;
        case BICYCLE:
            road = true;
            color = "#23C30B";
            baseImage = resources.modeBicyclePng();
            break;
        case BICYCLE_RENTAL:
            road = true;
            color = "#23C30B";
            baseImage = resources.modeBikeRentalPng();
            break;
        case CAR:
            road = true;
            color = "#333333";
            baseImage = resources.modeCarPng();
            break;
        default:
        case BUS:
            baseImage = resources.modeBusPng();
            break;
        case TRAM:
            baseImage = resources.modeTramPng();
            break;
        case FERRY:
            baseImage = resources.modeFerryPng();
            break;
        case GONDOLA:
            baseImage = resources.modeGondolaPng();
            break;
        case PLANE:
            baseImage = resources.modePlanePng();
            break;
        case RAIL:
            baseImage = resources.modeRailPng();
            break;
        case SUBWAY:
            baseImage = resources.modeSubwayPng();
            break;
        case TROLLEY:
            baseImage = resources.modeTrolleyPng();
            break;
    }
    final String url = baseImage.getSafeUri().asString();
    final Canvas canvas = Canvas.createIfSupported();
    if (canvas != null) {
        int width = baseImage.getWidth();
        int height = 1000;
        canvas.setCoordinateSpaceWidth(width);
        canvas.setCoordinateSpaceHeight(height);
        final Context2d context = canvas.getContext2d();
        context.setLineCap(LineCap.BUTT);
        if (road) {
            context.setStrokeStyle(CssColor.make(color));
            context.setLineWidth(4);
            for (int y = baseImage.getHeight(); y < 1000; y += 7) {
                context.moveTo(width / 2, y);
                context.lineTo(width / 2, y + 5);
            }
            context.stroke();
        } else {
            context.setStrokeStyle(CssColor.make("#000000"));
            context.setLineWidth(5);
            context.moveTo(width / 2, 0);
            context.lineTo(width / 2, height - 1);
            context.stroke();
            context.setStrokeStyle(CssColor.make(color));
            context.setLineWidth(4);
            context.moveTo(width / 2, 0);
            context.lineTo(width / 2, height - 1);
            context.stroke();
        }
        /*
			 * HACK ALERT! Image.onLoad event does not fire up when using
			 * internal resources (URL is internal data), but using the image
			 * immediately does not work (image does not seems to be ready). We
			 * defer the processing of the image rendering to a timer delayed a
			 * bit.
			 */
        Timer timer = new Timer() {

            @Override
            public void run() {
                Image image = new Image(url);
                ImageElement e = ImageElement.as(image.getElement());
                context.drawImage(e, 0, 0);
                String url2 = canvas.toDataUrl("image/png");
                widget.getElement().getStyle().setBackgroundImage("url('" + url2 + "')");
            }
        };
        timer.schedule(500);
    } else {
        widget.getElement().getStyle().setBackgroundImage("url('" + url + "')");
    }
}
Example 30
Project: crux-master  File: ImageProcessor.java View source code
/**
	 * Rotates an image to a certanly degree.
	 * @param degrees the degree of rotation. sample values: 90, 180, 270.
	 */
public void rotate(int degrees) {
    Context2d context = canvas.getContext2d();
    //clear canvas
    canvas.getContext2d().clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
    // move to the center of the canvas
    context.translate(canvas.getWidth() / 2, canvas.getHeight() / 2);
    // rotate the canvas to the specified degrees
    context.rotate(degrees * Math.PI / 180);
    // draw the image
    // since the context is rotated, the image will be rotated also
    context.drawImage(image.asImageElement(), -image.getWidth() / 2, image.getHeight() / 2);
    //restore previous rotation
    context.rotate(-degrees * Math.PI / 180);
    //translate back the image
    context.translate(-canvas.getWidth() / 2, -canvas.getHeight() / 2);
}
Example 31
Project: jagger-master  File: PlotSaver.java View source code
private void drawCanvas(Image imageOfPlot, SimplePlot plot, String plotHeader, String xAxisLabel) {
    Canvas canvasTmp = Canvas.createIfSupported();
    if (canvasTmp == null) {
        alert("Can not create canvas element in your browser.");
        return;
    }
    Context2d context = canvasTmp.getContext2d();
    ImageElement imageElement = ImageElement.as(imageOfPlot.getElement());
    // Width of plot image
    int plotWidth = plot.getOffsetWidth();
    // Height of plot image
    int plotHeight = plot.getOffsetHeight();
    // Font size of text in pixels
    int fontSize = 13;
    // Indent size in pixels. Used to separate all elements on final image and defines left indent of header or legend
    int indent = 5;
    JsArray<Series> series = plot.getModel().getSeries();
    // Calculate max width of legend label to avoid overlay
    int maxLegendLabelWidth = calculateLabelMaxWidth(series, context, fontSize);
    int legendRectangleWidth = (int) (fontSize * 1.5);
    int legendRectangleHeight = fontSize;
    // Total width of one series legend including rectangle with color, and indents.
    int oneSeriesLegendSize = legendRectangleWidth + 3 * indent + maxLegendLabelWidth;
    // Number of columns in legend
    int numberOfColumns = plotWidth / oneSeriesLegendSize;
    if (numberOfColumns == 0)
        numberOfColumns = 1;
    int legendHeight = calculateLegendHeight(series, numberOfColumns, fontSize, indent);
    // 2 * fontSize as we have Header of plot and X axis label
    // 3 * indent as we have indent from top to header,
    //                       indent between plot and header,
    //                       indent between plot and X axis label.
    int totalHeight = plotHeight + 2 * fontSize + 3 * indent + legendHeight;
    canvasTmp.setWidth(plotWidth + "px");
    canvasTmp.setHeight(totalHeight + "px");
    canvasTmp.setCoordinateSpaceWidth(plotWidth);
    canvasTmp.setCoordinateSpaceHeight(totalHeight);
    int currentY = 0;
    context.setFillStyle("black");
    context.setFont("bold " + fontSize + "px sans-serif");
    context.setTextAlign(Context2d.TextAlign.START);
    currentY += fontSize + indent;
    // add plot header
    context.fillText(plotHeader, indent, currentY);
    currentY += indent;
    // add image of plot
    //, imageElement.getWidth(), imageElement.getHeight());
    context.drawImage(imageElement, 0.0, currentY);
    currentY += plotHeight + indent;
    context.setFont(fontSize + "px sans-serif");
    context.setTextAlign(Context2d.TextAlign.CENTER);
    // add x axis label
    context.fillText(xAxisLabel, plotWidth / 2, currentY + fontSize / 2);
    currentY += fontSize + indent;
    int currentX = 0;
    for (int i = 0; i < series.length(); i++) {
        Series s = series.get(i);
        int curRecW = legendRectangleWidth;
        int curRecH = legendRectangleHeight;
        if (i % numberOfColumns == 0) {
            currentX = indent;
        } else {
            currentX += indent + oneSeriesLegendSize;
        }
        // add rectangle with color
        context.setFillStyle("gray");
        context.fillRect(currentX, currentY, curRecW, curRecH);
        context.setFillStyle("white");
        curRecW -= 2;
        curRecH -= 2;
        context.fillRect(currentX + 1, currentY + 1, curRecW, curRecH);
        context.setFillStyle(s.getColor());
        curRecW -= 2;
        curRecH -= 2;
        context.fillRect(currentX + 2, currentY + 2, curRecW, curRecH);
        context.setFillStyle("black");
        context.setTextAlign(Context2d.TextAlign.START);
        // add label of current series
        context.fillText(s.getLabel(), currentX + legendRectangleWidth + indent, currentY + fontSize - 2);
        if (i % numberOfColumns == numberOfColumns - 1) {
            currentY += fontSize + indent;
        }
    }
    // get url of png data created from canvas
    String url = canvasTmp.toDataUrl("image/png");
    // fire browser event to download png
    hiddenFrame.setUrl(url.replace("image/png", "image/octet-stream"));
}
Example 32
Project: KKPortal-master  File: UsageGraph.java View source code
/*
	 * This functions draws the data on the canvas with a potential shift to the left. It will
	 * slowly move the data points to the left while we are waiting for new data creating a smooth
	 * update of the graph.
	 * The constructor will ensure this function gets called every 0.1 seconds
	 */
private void drawPath(List<? extends Double> values, double shift) {
    if (values == null || values.isEmpty())
        return;
    Context2d context = canvas.getContext2d();
    //		context.setTransform(m11, m12, m21, m22, dx, dy)
    context.clearRect(0, 0, canvas.getOffsetWidth(), canvas.getCoordinateSpaceHeight());
    //		context.clear();
    context.beginPath();
    double pixelpersecond = canvas.getCoordinateSpaceWidth() / magicNumber;
    // How many missing values
    int o = Math.max(60 - values.size(), 0);
    context.moveTo((o - shift * 2 - 1) * pixelpersecond, canvas.getCoordinateSpaceHeight() * values.get(0));
    for (int i = 1, l = values.size(); i < l; i++) {
        double x = (i + o - shift * 2 - 1) * pixelpersecond;
        double y = canvas.getCoordinateSpaceHeight() * (1 - values.get(i));
        context.lineTo(x, y);
    }
    context.stroke();
}
Example 33
Project: ovirt-engine-master  File: AbstractLineChartProgressBarColumn.java View source code
private void drawChart(Canvas canvas, List<Integer> normalizedPoints) {
    Context2d context2d = canvas.getContext2d();
    context2d.clearRect(0, 0, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight());
    context2d.beginPath();
    int actualX = leftMargin;
    int stepSize = calculateStepSize(normalizedPoints, getChartWidth());
    int lastX = leftMargin;
    int lastY = calculateHeight(normalizedPoints.get(0), canvas.getCoordinateSpaceHeight());
    int lastPoint = normalizedPoints.get(0);
    context2d.moveTo(lastX, lastY);
    for (int point : normalizedPoints.subList(1, normalizedPoints.size())) {
        actualX += stepSize;
        lastX = actualX;
        lastY = calculateHeight(point, canvas.getCoordinateSpaceHeight());
        lastPoint = point;
        context2d.lineTo(lastX, lastY);
    }
    context2d.setLineWidth(lineWidth);
    //$NON-NLS-1$
    context2d.setStrokeStyle(chartLineColor);
    context2d.stroke();
    drawLineDecoration(context2d, lastX, lastY, lastPoint);
}
Example 34
Project: gef-gwt-master  File: LightweightSystem.java View source code
@Override
public Graphics getGraphics(Rectangle region) {
    if (gg == null) {
        gc = new GC(new GWTDrawable() {

            @Override
            public long internal_new_GC(GCData data) {
                return 0;
            }

            @Override
            public void internal_dispose_GC(long handle, GCData data) {
            }

            @Override
            public Context2d internal_getContext() {
                return ((com.google.gwt.canvas.client.Canvas) c.getNativeWidget()).getContext2d();
            }
        });
        gg = new SWTGraphics(gc);
    // gc.setClipping(region.x, region.y, region.width,
    // region.height);
    }
    gg.setBackgroundColor(ColorConstants.white);
    return gg;
}
Example 35
Project: HTML5-Player-deprecated-master  File: Sprite.java View source code
/**
	 *
	 * @param relativeX
	 * @param relativeY
	 * @return
	 */
public boolean processOnTouch(int relativeX, int relativeY) {
    //Create temp canvas with the current look only to determine click (alpha) 
    Canvas temp = Canvas.createIfSupported();
    temp.setWidth(Scene.get().getCanvas().getCoordinateSpaceWidth() + "px");
    temp.setHeight(Scene.get().getCanvas().getCoordinateSpaceHeight() + "px");
    temp.setCoordinateSpaceWidth(Scene.get().getCanvas().getCoordinateSpaceWidth());
    temp.setCoordinateSpaceHeight(Scene.get().getCanvas().getCoordinateSpaceHeight());
    LookData lookData = look.getLookData();
    if (lookData == null)
        return false;
    double size = look.getSize();
    double width = (double) lookData.getWidth() * size;
    double height = (double) lookData.getHeight() * size;
    double x = -width / 2;
    double y = -height / 2;
    Context2d context = temp.getContext2d();
    context.translate(look.getXPosition(), look.getYPosition());
    context.rotate((-look.getRotation()) * Math.PI / 180);
    context.drawImage((ImageElement) currentLook.getElement().cast(), x, y, width, height);
    if (context.getImageData(relativeX, relativeY, 1, 1).getAlphaAt(0, 0) == 0) {
        return false;
    }
    if (currentLook == null || !look.isVisible())
        return false;
    double xPosition = look.getXPosition();
    double yPosition = look.getYPosition();
    double newSize = look.getSize();
    LookData newLookData = look.getLookData();
    double widthHalf = ((double) newLookData.getWidth() * newSize) / 2;
    double heightHalf = ((double) newLookData.getHeight() * newSize) / 2;
    if (xPosition + widthHalf > relativeX && xPosition - widthHalf < relativeX && yPosition + heightHalf > relativeY && yPosition - heightHalf < relativeY) {
        CatrobatDebug.info("Sprite " + this.name + " got touched");
        return true;
    }
    return false;
}
Example 36
Project: GlycanBuilderVaadin7Version-master  File: CanvasConnector.java View source code
@Override
protected void init() {
    super.init();
    mouseMoveHandler = new MouseMoveHandler() {

        @Override
        public void onMouseMove(MouseMoveEvent event) {
            int x = event.getClientX() - DOM.getAbsoluteLeft(getWidget().getElement());
            int y = event.getClientY() - DOM.getAbsoluteTop(getWidget().getElement());
            if (enableMouseSelectionMode) {
                if (mouseDown && ((x - lastXPosMove > 10 || x - lastXPosMove < -10) || ((y - lastYPosMove > 10 || y - lastYPosMove < -10)))) {
                    lastXPosMove = x;
                    lastYPosMove = y;
                    int x1, y1, width, height;
                    if (mouseDownPoint_x > x) {
                        x1 = x;
                        width = mouseDownPoint_x - x1;
                    } else {
                        x1 = mouseDownPoint_x;
                        width = x - x1;
                    }
                    if (mouseDownPoint_y > y) {
                        y1 = y;
                        height = mouseDownPoint_y - y1;
                    } else {
                        y1 = mouseDownPoint_y;
                        height = y - y1;
                    }
                    clientRpc.daveClear();
                    clientRpc.redraw();
                    clientRpc.saveContext();
                    clientRpc.setLineWidth(1d);
                    clientRpc.setStrokeStyle("#000");
                    clientRpc.strokeRect((double) x1, (double) y1, (double) width, (double) height, false);
                    clientRpc.restoreContext();
                }
            }
        }
    };
    getWidget().addClickHandler(new ClickHandler() {

        public void onClick(ClickEvent event) {
            MouseEventDetails med = MouseEventDetailsBuilder.buildMouseEventDetails(event.getNativeEvent(), getWidget().getElement());
            rpc.clicked(med);
        }
    });
    getWidget().addMouseDownHandler(new MouseDownHandler() {

        @Override
        public void onMouseDown(MouseDownEvent event) {
            int x = event.getClientX() - DOM.getAbsoluteLeft(getWidget().getElement());
            int y = event.getClientY() - DOM.getAbsoluteTop(getWidget().getElement());
            if (enableMouseSelectionMode) {
                mouseDownPoint_x = x;
                mouseDownPoint_y = y;
                lastXPosMove = x;
                lastYPosMove = y;
                mouseDown = true;
                //register new mouse move listener
                mouseMoveRegistration = getWidget().addMouseMoveHandler(mouseMoveHandler);
            }
            rpc.mouseDown(x, y);
        }
    });
    getWidget().addMouseUpHandler(new MouseUpHandler() {

        @Override
        public void onMouseUp(MouseUpEvent event) {
            int x = event.getClientX() - DOM.getAbsoluteLeft(getWidget().getElement());
            int y = event.getClientY() - DOM.getAbsoluteTop(getWidget().getElement());
            if (enableMouseSelectionMode) {
                clientRpc.daveClear();
                clientRpc.redraw();
                if (mouseMoveRegistration != null) {
                    mouseMoveRegistration.removeHandler();
                    mouseMoveRegistration = null;
                }
                mouseDown = false;
            //TODO					
            //cachedScrollTop=getWidget().getElement().getParentElement().getScrollTop();
            //cachedScrollLeft=getWidget().getElement().getParentElement().getScrollLeft();
            }
            rpc.mouseUp(x, y);
        }
    });
    clientRpc = new CanvasClientRpc() {

        private static final long serialVersionUID = -7521521510799765779L;

        private final Context2d ctx = getWidget().getContext2d();

        @Override
        public void fillRect(final Double startX, final Double startY, final Double width, final Double height) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.fillRect(startX, startY, width, height);
                }
            });
        }

        @Override
        public void drawImage1(final String url, final Double offsetX, final Double offsetY) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    VConsole.log("Drawing " + url + "\n at " + offsetX + "," + offsetY);
                    ctx.drawImage(ImageElement.as(new Image(url).getElement()), offsetX, offsetY);
                    VConsole.log("Drawing complete");
                }
            });
        }

        @Override
        public void drawImage2(final String url, final Double offsetX, final Double offsetY, final Double imageWidth, final Double imageHeight) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    VConsole.log("Drawing " + url + "\n at " + offsetX + "," + offsetY + " w" + imageWidth + " h" + imageHeight);
                    ctx.drawImage(ImageElement.as(new Image(url).getElement()), offsetX, offsetY, imageWidth, imageHeight);
                    VConsole.log("Drawing complete");
                }
            });
        }

        @Override
        public void drawImage3(final String url, final Double sourceX, final Double sourceY, final Double sourceWidth, final Double sourceHeight, final Double destX, final Double destY, final Double destWidth, final Double destHeight) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    VConsole.log("Drawing " + url + "\n from " + sourceX + "," + sourceY + " w" + sourceWidth + " h" + sourceHeight + " to " + destX + "," + destY + " " + destWidth + "x" + destHeight);
                    ctx.drawImage(ImageElement.as(new Image(url).getElement()), sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
                    VConsole.log("Drawing complete");
                }
            });
        }

        @Override
        public void fill() {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.fill();
                }
            });
        }

        @Override
        public void fillText(final String text, final Double x, final Double y, final Double maxWidth) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.fillText(text, x, y, maxWidth);
                }
            });
        }

        @Override
        public void setFont(final String font) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setFont(font);
                }
            });
        }

        @Override
        public void setTextBaseline(final String textBaseline) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setTextBaseline(textBaseline);
                }
            });
        }

        @Override
        public void lineTo(final Double x, final Double y) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.lineTo(x, y);
                }
            });
        }

        @Override
        public void moveTo(final Double x, final Double y) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.moveTo(x, y);
                }
            });
        }

        @Override
        public void quadraticCurveTo(final Double cpx, final Double cpy, final Double x, final Double y) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.quadraticCurveTo(cpx, cpy, x, y);
                }
            });
        }

        @Override
        public void rect(final Double startX, final Double startY, final Double rectWidth, final Double rectHeight) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.rect(startX, startY, rectWidth, rectHeight);
                }
            });
        }

        @Override
        public void rotate(final Double angle) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.rotate(angle);
                }
            });
        }

        @Override
        public void setFillStyle(final String color) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setFillStyle(color);
                }
            });
        }

        @Override
        public void setLineCap(final String lineCap) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setLineCap(lineCap);
                }
            });
        }

        @Override
        public void setLineJoin(final String lineJoin) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setLineJoin(lineJoin);
                }
            });
        }

        @Override
        public void setLineWidth(final Double lineWidth) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setLineWidth(lineWidth);
                }
            });
        }

        @Override
        public void setMiterLimit(final Double miterLimit) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setMiterLimit(miterLimit);
                }
            });
        }

        @Override
        public void strokeRect(final Double startX, final Double startY, final Double strokeWidth, final Double strokeHeight) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.strokeRect(startX, startY, strokeWidth, strokeHeight);
                }
            });
        }

        @Override
        public void transform(final Double m11, final Double m12, final Double m21, final Double m22, final Double dx, final Double dy) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.transform(m11, m12, m21, m22, dx, dy);
                }
            });
        }

        @Override
        public void arc(final Double x, final Double y, final Double radius, final Double startAngle, final Double endAngle, Boolean antiClockwise) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.arc(x, y, radius, startAngle, endAngle);
                }
            });
        }

        @Override
        public void translate(final Double x, final Double y) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.translate(x, y);
                }
            });
        }

        @Override
        public void scale(final Double x, final Double y) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.scale(x, y);
                }
            });
        }

        @Override
        public void stroke() {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.stroke();
                }
            });
        }

        @Override
        public void saveContext() {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.save();
                }
            });
        }

        @Override
        public void restoreContext() {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.restore();
                }
            });
        }

        @Override
        public void setStrokeStyle(final String rgb) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setStrokeStyle(rgb);
                }
            });
        }

        @Override
        public void beginPath() {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.beginPath();
                }
            });
        }

        @Override
        public void clear() {
            ctx.clearRect(0, 0, getWidget().getCoordinateSpaceWidth(), getWidget().getCoordinateSpaceHeight());
            clearCommands();
        }

        @Override
        public void setGlobalAlpha(final Double alpha) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setGlobalAlpha(alpha);
                }
            });
        }

        @Override
        public void closePath() {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.closePath();
                }
            });
        }

        @Override
        public void setGlobalCompositeOperation(final String mode) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setGlobalCompositeOperation(mode);
                }
            });
        }

        @Override
        public void setGradientFillStyle(final String gradientName) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    if (gradients.containsKey(gradientName)) {
                        ctx.setFillStyle(gradients.get(gradientName));
                    } else {
                        System.err.println("setGradientFillStyle: Gradient not foud with name " + gradientName);
                    }
                }
            });
        }

        @Override
        public void createLinearGradient(final String name, final Double x0, final Double y0, final Double x1, final Double y1) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    CanvasGradient newGradient = ctx.createLinearGradient(x0, y0, x1, y1);
                    gradients.put(name, newGradient);
                }
            });
        }

        @Override
        public void createRadialGradient(final String name, final Double x0, final Double y0, final Double r0, final Double x1, final Double y1, final Double r1) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    CanvasGradient newGradient = ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
                    gradients.put(name, newGradient);
                }
            });
        }

        @Override
        public void setGradientStrokeStyle(final String gradientName) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    if (gradients.containsKey(gradientName)) {
                        ctx.setStrokeStyle(gradients.get(gradientName));
                    } else {
                        System.err.println("setGradientStrokeStyle: Gradient not found with name " + gradientName);
                    }
                }
            });
        }

        @Override
        public void addColorStop(final String gradientName, final Double offset, final String color) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    if (gradients.containsKey(gradientName)) {
                        gradients.get(gradientName).addColorStop(offset, color);
                    } else {
                        System.err.println("addColorStop: Gradient not foud with name " + gradientName);
                    }
                }
            });
        }

        @Override
        public void loadImages(final String[] urls) {
            final List<String> imagesToLoad = new ArrayList<String>();
            imagesToLoad.addAll(Arrays.asList(urls));
            for (final String url : urls) {
                final Image image = new Image(url);
                image.addLoadHandler(new LoadHandler() {

                    @Override
                    public void onLoad(LoadEvent event) {
                        RootPanel.get().remove(image);
                        imagesToLoad.remove(url);
                        if (imagesToLoad.isEmpty())
                            rpc.imagesLoaded();
                    }
                });
                image.addErrorHandler(new ErrorHandler() {

                    @Override
                    public void onError(ErrorEvent event) {
                        RootPanel.get().remove(image);
                        imagesToLoad.remove(url);
                        if (imagesToLoad.isEmpty())
                            rpc.imagesLoaded();
                    }
                });
                // Force loading of the image
                image.setVisible(false);
                RootPanel.get().add(image);
            }
        }

        @Override
        public void setBackgroundColor(final String color) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    DOM.setStyleAttribute(getWidget().getElement(), "backgroundColor", color);
                }
            });
        }

        @Override
        public void redraw() {
            for (Command command : commands) {
                command.execute();
            }
        }

        @Override
        public void daveClear() {
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.clearRect(0, 0, getWidget().getCoordinateSpaceWidth(), getWidget().getCoordinateSpaceHeight());
        }

        @Override
        public void strokeRect(Double startX, Double startY, Double strokeWidth, Double strokeHeight, boolean saveInCommands) {
            ctx.strokeRect(startX, startY, strokeWidth, strokeHeight);
        }

        @Override
        public void enableMouseSelectionRectangle(boolean enable) {
            enableMouseSelectionMode = enable;
        }

        @Override
        public void bezierCurveTo(final Double cp1x, final Double cp1y, final Double cp2x, final Double cp2y, final Double x, final Double y) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
                }
            });
        }

        @Override
        public void textAlign(final String textAlign) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.setTextAlign(textAlign);
                }
            });
        }

        @Override
        public void fillText(final String text, final double x, final double y) {
            runCommand(new Command() {

                @Override
                public void execute() {
                    ctx.fillText(text, x, y);
                }
            });
        }

        @Override
        public void setMinimumSize(int width, int height) {
            if (width > getWidget().getCoordinateSpaceWidth()) {
                getWidget().setWidth(width + "px");
            }
            if (height > getWidget().getCoordinateSpaceHeight()) {
                getWidget().setHeight(height + "px");
            }
        }
    };
    registerRpc(CanvasClientRpc.class, clientRpc);
}
Example 37
Project: gwt-three.js-test-master  File: PhysicalExample.java View source code
@Override
public void init() {
    clock = THREE.Clock();
    WIDTH = (int) getWindowInnerWidth();
    HEIGHT = (int) getWindowInnerHeight();
    windowHalfX = (int) (getWindowInnerWidth() / 2);
    windowHalfY = (int) (getWindowInnerHeight() / 2);
    FocusPanel container = createContainerPanel();
    // renderer
    renderer = THREE.WebGLRenderer(WebGLRendererParameter.create().antialias(true));
    renderer.setPixelRatio(GWTThreeUtils.getWindowDevicePixelRatio());
    renderer.setSize(WIDTH, HEIGHT);
    container.getElement().appendChild(renderer.getDomElement());
    //renderer.shadowMap.enabled = true;
    renderer.getShadowMap().setEnabled(true);
    //renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    renderer.getShadowMap().setType(THREE.PCFSoftShadowMap);
    //
    //renderer.gammaInput = true;
    renderer.setGammaInput(true);
    //renderer.gammaOutput = true;
    renderer.setGammaOutput(true);
    // scene
    scene = THREE.Scene();
    scene.setFog(THREE.Fog(0x00aaff, 1000, FAR));
    // camera
    camera = THREE.PerspectiveCamera(45, getWindowInnerWidth() / getWindowInnerHeight(), 2, FAR);
    camera.getPosition().set(500, 400, 1200);
    cubeCamera = THREE.CubeCamera(1, FAR, 128);
    scene.add(cubeCamera);
    Canvas x = Canvas.createIfSupported();
    Context2d xc = x.getContext2d();
    x.setSize(128 + "px", 128 + "px");
    xc.setFillStyle("#fff");
    xc.fillRect(0, 0, 128, 128);
    xc.setFillStyle("#000");
    xc.fillRect(0, 0, 64, 64);
    xc.setFillStyle("#999");
    xc.fillRect(32, 32, 32, 32);
    xc.setFillStyle("#000");
    xc.fillRect(64, 64, 64, 64);
    xc.setFillStyle("#555");
    xc.fillRect(96, 96, 32, 32);
    CanvasTexture texturePattern = // var
    THREE.CanvasTexture(// var
    x.getCanvasElement());
    // texturePattern
    // =
    // new
    // THREE.CanvasTexture(
    // x
    // )
    // texturePattern.format =
    texturePattern.setFormat(THREE.RGBFormat);
    // THREE.RGBFormat;
    // texturePattern.repeat.set(
    texturePattern.getRepeat().set(1000, 1000);
    // 1000, 1000 );
    // texturePattern.wrapS =
    texturePattern.setWrapS(THREE.RepeatWrapping);
    // THREE.RepeatWrapping;
    // texturePattern.wrapT =
    texturePattern.setWrapT(THREE.RepeatWrapping);
    // THREE.RepeatWrapping;
    Texture textureSquares = // var
    ImageUtils.loadTexture(// var
    "textures/patterns/bright_squares256.png");
    // textureSquares
    // =
    // THREE.ImageUtils.loadTexture(
    // "textures/patterns/bright_squares256.png"
    // );
    // textureSquares.repeat.set( 50,
    textureSquares.getRepeat().set(50, 50);
    // 50 );
    // textureSquares.wrapS =
    textureSquares.setWrapS(THREE.RepeatWrapping);
    // textureSquares.wrapT
    // =
    // THREE.RepeatWrapping;
    textureSquares.setWrapT(THREE.RepeatWrapping);
    // textureSquares.magFilter
    textureSquares.setMagFilter(THREE.NearestFilter);
    // =
    // THREE.NearestFilter;
    // textureSquares.format =
    textureSquares.setFormat(THREE.RGBFormat);
    // THREE.RGBFormat;
    Texture textureNoiseColor = // var
    ImageUtils.loadTexture(// var
    "textures/disturb.jpg");
    // textureNoiseColor
    // =
    // THREE.ImageUtils.loadTexture(
    // "textures/disturb.jpg"
    // );
    // textureNoiseColor.repeat.set(
    textureNoiseColor.getRepeat().set(1, 1);
    // 1, 1 );
    // textureNoiseColor.wrapS
    textureNoiseColor.setWrapS(THREE.RepeatWrapping);
    // =
    // textureNoiseColor.wrapT
    // =
    // THREE.RepeatWrapping;
    textureNoiseColor.setWrapT(THREE.RepeatWrapping);
    // textureNoiseColor.format
    textureNoiseColor.setFormat(THREE.RGBFormat);
    // = THREE.RGBFormat;
    Texture textureLava = // var
    ImageUtils.loadTexture(// var
    "textures/lava/lavatile.jpg");
    // textureLava
    // =
    // THREE.ImageUtils.loadTexture(
    // "textures/lava/lavatile.jpg"
    // );
    // textureLava.repeat.set( 6, 2 );
    textureLava.getRepeat().set(6, 2);
    // textureLava.wrapS =
    textureLava.setWrapS(THREE.RepeatWrapping);
    // textureLava.wrapT =
    // THREE.RepeatWrapping;
    textureLava.setWrapT(THREE.RepeatWrapping);
    // textureLava.format =
    textureLava.setFormat(THREE.RGBFormat);
    // THREE.RGBFormat;
    // var path =
    String path = "textures/cube/SwedishRoyalCastle/";
    // "textures/cube/SwedishRoyalCastle/";
    // var format = '.jpg';
    String format = ".jpg";
    String[] urls = { path + "px" + format, path + "nx" + format, path + "py" + format, path + "ny" + format, path + "pz" + format, path + "nz" + format };
    ;
    Texture reflectionCube = // var
    ImageUtils.loadTextureCube(// var
    JavaScriptUtils.toArray(urls));
    // reflectionCube
    // =
    // THREE.ImageUtils.loadTextureCube(
    // urls
    // );
    // ground
    MeshPhongMaterial groundMaterial = THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial().shininess(80).color(0xffffff).specular(0xffffff).map(// var groundMaterial = new
    textureSquares));
    // THREE.MeshPhongMaterial( {shininess:
    // 80,color: 0xffffff,specular:
    // 0xffffff,map: textureSquares} );
    PlaneBufferGeometry planeGeometry = // var
    THREE.PlaneBufferGeometry(// var
    100, // var
    100);
    // planeGeometry
    // =
    // new
    // THREE.PlaneBufferGeometry(
    // 100,
    // 100
    // );
    // var ground =
    Mesh ground = THREE.Mesh(planeGeometry, groundMaterial);
    // new
    // THREE.Mesh(
    // planeGeometry,
    // groundMaterial
    // );
    // ground.position.set( 0, 0, 0 );
    ground.getPosition().set(0, 0, 0);
    // ground.rotation.x = - Math.PI
    ground.getRotation().setX(-Math.PI / 2);
    // / 2;
    // ground.scale.set( 1000, 1000,
    ground.getScale().set(1000, 1000, 1000);
    // 1000 );
    // ground.receiveShadow = true;
    ground.setReceiveShadow(true);
    scene.add(ground);
    // materials
    Shader shader = ShaderLib.cube();
    // shader.uniforms[
    shader.uniforms().set("tCube", cubeCamera.getRenderTarget());
    // "tCube"
    // ].texture
    // =
    // cubeCamera.renderTarget;
    // shader.uniforms[ "tFlip" ].value =
    shader.uniforms().set("tFlip", 1);
    // 1;
    ShaderMaterial materialCube = THREE.ShaderMaterial(GWTParamUtils.ShaderMaterial().fragmentShader(shader.fragmentShader()).vertexShader(shader.vertexShader()).uniforms(// var
    shader.uniforms()));
    // materialCube
    // =
    // new
    // THREE.ShaderMaterial(
    // {fragmentShader:
    // shader.fragmentShader,vertexShader:
    // shader.vertexShader,uniforms:
    // shader.uniforms}
    // );
    MeshPhongMaterial materialLambert = // var
    THREE.MeshPhongMaterial(// var
    GWTParamUtils.MeshPhongMaterial().shininess(50).color(0xffffff).map(textureNoiseColor));
    // materialLambert
    // =
    // new
    // THREE.MeshPhongMaterial(
    // {
    // shininess:
    // 50,
    // color:
    // 0xffffff,
    // map:
    // textureNoiseColor
    // }
    // );
    MeshPhongMaterial materialPhong = THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial().shininess(50).color(0xffffff).specular(0x999999).map(// var materialPhong = new
    textureLava));
    // THREE.MeshPhongMaterial( { shininess: 50,
    // color: 0xffffff, specular: 0x999999, map:
    // textureLava } );
    MeshPhongMaterial materialPhongCube = THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial().shininess(50).color(0xffffff).specular(0x999999).envMap(// var
    cubeCamera.getRenderTarget().gwtCastTexture()));
    // materialPhongCube
    // = new
    // THREE.MeshPhongMaterial(
    // {
    // shininess:
    // 50,
    // color:
    // 0xffffff,
    // specular:
    // 0x999999,
    // envMap:
    // cubeCamera.renderTarget
    // } );
    // stats
    // object
    SphereGeometry sphereGeometry = // var
    THREE.SphereGeometry(// var
    100, // var
    64, // var
    32);
    // sphereGeometry
    // =
    // new
    // THREE.SphereGeometry(
    // 100,
    // 64,
    // 32
    // );
    TorusGeometry torusGeometry = // var
    THREE.TorusGeometry(// var
    240, // var
    60, // var
    32, // var
    64);
    // torusGeometry
    // =
    // new
    // THREE.TorusGeometry(
    // 240,
    // 60,
    // 32,
    // 64
    // );
    BoxGeometry cubeGeometry = // var
    THREE.BoxGeometry(// var
    150, // var
    150, // var
    150);
    // cubeGeometry
    // = new
    // THREE.BoxGeometry(
    // 150, 150,
    // 150 );
    addObject(torusGeometry, materialPhong, 0, 100, 0, 0);
    addObject(cubeGeometry, materialLambert, 350, 75, 300, 0);
    mesh = addObject(sphereGeometry, materialPhongCube, 350, 100, -350, 0);
    BoxGeometry bigCube = THREE.BoxGeometry(50, 500, 50);
    BoxGeometry midCube = THREE.BoxGeometry(50, 200, 50);
    BoxGeometry smallCube = THREE.BoxGeometry(100, 100, 100);
    addObjectColor(bigCube, 0xff0000, -500, 250, 0, 0);
    addObjectColor(smallCube, 0xff0000, -500, 50, -150, 0);
    addObjectColor(midCube, 0x00ff00, 500, 100, 0, 0);
    addObjectColor(smallCube, 0x00ff00, 500, 50, -150, 0);
    addObjectColor(midCube, 0x0000ff, 0, 100, -500, 0);
    addObjectColor(smallCube, 0x0000ff, -150, 50, -500, 0);
    addObjectColor(midCube, 0xff00ff, 0, 100, 500, 0);
    addObjectColor(smallCube, 0xff00ff, -150, 50, 500, 0);
    addObjectColor(THREE.BoxGeometry(500, 10, 10), 0xffff00, 0, 600, 0, Math.PI / 4);
    addObjectColor(THREE.BoxGeometry(250, 10, 10), 0xffff00, 0, 600, 0, 0);
    addObjectColor(THREE.SphereGeometry(100, 32, 26), 0xffffff, -300, 100, 300, 0);
    JSONLoader loader = THREE.JSONLoader();
    loader.load("models/animated/sittingBox.js", new JSONLoadHandler() {

        @Override
        public void loaded(Geometry geometry, JsArray<Material> materials) {
            //var morphMaterial = new THREE.MeshPhongMaterial( { color: 0x000000, specular: 0xff9900, shininess: 50, morphTargets: true, side: THREE.DoubleSide, shading: THREE.FlatShading } );
            MeshPhongMaterial morphMaterial = THREE.MeshPhongMaterial(GWTParamUtils.MeshPhongMaterial().color(0x000000).specular(0xff9900).shininess(50).morphTargets(true).side(THREE.DoubleSide).shading(THREE.FlatShading));
            //mesh = new THREE.Mesh( geometry, morphMaterial );
            mesh = THREE.Mesh(geometry, morphMaterial);
            //mixer = new THREE.AnimationMixer( mesh );
            mixer = THREE.AnimationMixer(mesh);
            //mixer.addAction( new THREE.AnimationAction( geometry.animations[0] ).warpToDuration( 10 ) );
            mixer.clipAction(geometry.getAnimations().get(0)).setDuration(10).play();
            //var s = 200;
            double s = 200;
            //mesh.scale.set( s, s, s );
            mesh.getScale().set(s, s, s);
            //morph.setDuration(8000);////morph.duration = 8000;
            //morph.setMirroredLoop(true);////morph.mirroredLoop = true;
            //mesh.castShadow = true;
            mesh.setCastShadow(true);
            //mesh.receiveShadow = true;
            mesh.setReceiveShadow(true);
            scene.add(mesh);
        }
    });
    double sunIntensity = 0.3;
    double pointIntensity = 1;
    int pointColor = 0xffaa00;
    if (DAY) {
        sunIntensity = 1;
        pointIntensity = 0.5;
        pointColor = 0xffffff;
    }
    //ambientLight = new THREE.AmbientLight( 0x3f2806 );
    ambientLight = THREE.AmbientLight(0x3f2806);
    scene.add(ambientLight);
    //pointLight = new THREE.PointLight( 0xffaa00, pointIntensity, 5000 );
    pointLight = THREE.PointLight(0xffaa00, pointIntensity, 5000);
    //pointLight.position.set( 0, 0, 0 );
    pointLight.getPosition().set(0, 0, 0);
    scene.add(pointLight);
    //sunLight = new THREE.SpotLight( 0xffffff, sunIntensity, 0, Math.PI/2, 1 );
    sunLight = THREE.SpotLight(0xffffff, sunIntensity, 0, Math.PI / 2, 1);
    //sunLight.position.set( 1000, 2000, 1000 );
    sunLight.getPosition().set(1000, 2000, 1000);
    //sunLight.castShadow = true;
    sunLight.setCastShadow(true);
    //sunLight.shadowBias = -0.0002;
    sunLight.setShadowBias(-0.0002);
    //sunLight.shadowCameraNear = 750;
    sunLight.setShadowCameraNear(750);
    //sunLight.shadowCameraFar = 4000;
    sunLight.setShadowCameraFar(4000);
    //sunLight.shadowCameraFov = 30;
    sunLight.setShadowCameraFov(30);
    //sunLight.shadowCameraVisible = false;
    sunLight.setShadowCameraVisible(false);
    scene.add(sunLight);
    //trackball consume keydown event.this is the way to add keydown on root
    //TODO method
    GWTUtils.addKeyDownHandlerToDocument(new KeyDownHandler() {

        @Override
        public void onKeyDown(KeyDownEvent event) {
            if (event.getNativeKeyCode() == 78) {
                if (tweenDirection == 1) {
                    tweenDay.stop();
                    tweenNight.start();
                    tweenDirection = -1;
                } else {
                    tweenNight.stop();
                    tweenDay.start();
                    tweenDirection = 1;
                }
            }
        }
    });
    //control
    //controls = new THREE.TrackballControls( camera, renderer.domElement );
    controls = THREEExp.TrackballControls(camera, renderer.getDomElement());
    //controls.target.set( 0, 120, 0 );
    controls.getTarget().set(0, 120, 0);
    //controls.rotateSpeed = 1.0;
    controls.setRotateSpeed(1.0);
    //controls.zoomSpeed = 1.2;
    controls.setZoomSpeed(1.2);
    //controls.panSpeed = 0.8;
    controls.setPanSpeed(0.8);
    //controls.noZoom = false;
    controls.setNoZoom(false);
    //controls.noPan = false;
    controls.setNoPan(false);
    //controls.staticMoving = true;
    controls.setStaticMoving(true);
    //controls.dynamicDampingFactor = 0.15;
    controls.setDynamicDampingFactor(0.15);
    //controls.keys = [ 65, 83, 68 ];
    controls.setKeys(JavaScriptUtils.toArray(new int[] { 65, 83, 68 }));
    //Tween
    tweenDirection = -1;
    parameters = JSParameter.createParameter().set("control", 0);
    tweenDay = TWEEN.Tween(parameters).to("control", 1, 1000).easing(TWEEN.Easing_Exponential_Out());
    tweenNight = TWEEN.Tween(parameters).to("control", 0, 1000).easing(TWEEN.Easing_Exponential_Out());
    stats = Stats.create();
    stats.setPosition(0, 0);
    container.getElement().appendChild(stats.domElement());
    //add html info
    container.add(createAbsoluteHTML("<div style='text:white'><a href='http://threejs.org' target='_blank'>three.js</a>  - test</a>", 100, 10));
    //handle resize & gui
    initResizeHandlerAndGUI();
//setDebugAnimateOneTimeOnly(true);
}
Example 38
Project: openSDX-master  File: OSDXKeyserverFE.java View source code
private void drawNumberOutline(Context2d g, int no, double px, double py) {
    int ox = -2;
    if (no < 10) {
        ox = -2;
    } else if (no < 100) {
        ox = -6;
    } else {
        ox = -10;
    }
    g.setStrokeStyle(CssColor.make("white"));
    g.setFillStyle(CssColor.make("white"));
    g.strokeText("" + no, px + ox, py + 3);
    g.setStrokeStyle(CssColor.make("black"));
    g.setFillStyle(CssColor.make("black"));
    g.fillText("" + no, px + ox, py + 3);
}
Example 39
Project: libgdx-master  File: Pixmap.java View source code
public Context2d getContext() {
    ensureCanvasExists();
    return context;
}