com.google.gwt.canvas.client.Canvas Java Examples

The following examples show how to use com.google.gwt.canvas.client.Canvas. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ImageCanvasTest.java    From TGAReader with MIT License 6 votes vote down vote up
private 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++) { // ABGR
		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);
	
	canvas.getElement().getStyle().setMargin(4, Unit.PX);
	
	return canvas;
	
}
 
Example #2
Source File: TexturedCube.java    From TGAReader with MIT License 6 votes vote down vote up
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 #3
Source File: TextMetricsCalculator.java    From jetpad-projectional-open-source with Apache License 2.0 5 votes vote down vote up
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 #4
Source File: SVGToolBarImpl.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Drawing function
 *
 * @param canvas
 */
private void draw(Canvas canvas) {
  Context2d context2d = canvas.getContext2d();
  GraphicsContext ctx = new GraphicsContext(context2d);
  drawButtons(ctx);
  drawESRButtons(ctx);
  drawHover(ctx);
}
 
Example #5
Source File: Util.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void scaleCanvas(Canvas canvas, int width, int height) {
  canvas.setWidth(width + "px");
  canvas.setHeight(height + "px");

  Context2d ctx = canvas.getContext2d();

  double ratio = Util.getDevicePixelRatio();
  canvas.setCoordinateSpaceWidth((int)(width * ratio));
  canvas.setCoordinateSpaceHeight((int)(height * ratio));
  ctx.scale(ratio, ratio);
}
 
Example #6
Source File: DrawArea.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void draw(Canvas canvas) {
  long fg = builder.getForegroundColor();
  Context2d context2d = canvas.getContext2d();
  int w = (int) model.getDisplaySize().getWidth();
  int h = (int) model.getDisplaySize().getHeight();

  int displayMode = model.getDisplayMode();

  drawBackground(context2d, w, h);

  if (isReaction()) {
    model.analyzeFragmentMembership();
    if (model.needsLayout())
      model.cleanReaction(true);
  }

  AbstractExtendedDepictor depictor = createDepictor();
  depictor.setDisplayMode(displayMode);

  if (model.needsLayout()) {
    depictor.updateCoords(null, new java.awt.geom.Rectangle2D.Double(0, 0, (float) w, (float) h),
        AbstractDepictor.cModeInflateToMaxAVBL);
  }
  model.needsLayout(false);

  depictor.paint(context2d);
  // Let the actions draw if needed e.g. NewChainAction
  if (action != null) {
    GraphicsContext ctx = new GraphicsContext(context2d);
    ctx.save();
    ctx.setStroke(fg);
    ctx.setFill(fg);
    action.paint(ctx);
    ctx.restore();
  }
}
 
Example #7
Source File: StructureView.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void drawIDCode(CanvasElement el, String idcode, String coordinates, int displayMode,
        String[] atomText) {
    Canvas canvas = Canvas.wrap(el);
    if (idcode != null && idcode.length() > 0) {
        String combined = idcode + (coordinates != null ? " " + coordinates : "");
        Context2d ctx = canvas.getContext2d();
        drawMolecule(ctx, combined, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight(),
                displayMode, atomText);
    }
}
 
Example #8
Source File: StructureView.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void draw(CanvasElement el, String idcode, String coordinates) {
    Canvas canvas = Canvas.wrap(el);
    if (idcode != null && idcode.length() > 0) {
        String combined = idcode + (coordinates != null ? " " + coordinates : "");
        Context2d ctx = canvas.getContext2d();
        drawMolecule(ctx, combined, canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight());
    }
}
 
Example #9
Source File: ImageCanvasTest.java    From TGAReader with MIT License 5 votes vote down vote up
private void addTGACanvas(String url) {
	XMLHttpRequest request = XMLHttpRequest.create();
	request.open("GET", url);
	request.setResponseType(ResponseType.ArrayBuffer);
	request.setOnReadyStateChange(new ReadyStateChangeHandler() {
		@Override
		public void onReadyStateChange(XMLHttpRequest xhr) {
			if(xhr.getReadyState() == XMLHttpRequest.DONE) {
				if(xhr.getStatus() >= 400) {
					// error
					System.out.println("Error");
				}
				else {
					try {
						ArrayBuffer arrayBuffer = xhr.getResponseArrayBuffer();
						Uint8ArrayNative u8array = Uint8ArrayNative.create(arrayBuffer);
						byte [] buffer = new byte[u8array.length()];
						for(int i=0; i<buffer.length; i++) {
							buffer[i] = (byte)u8array.get(i);
						}
						int pixels [] = TGAReader.read(buffer, TGAReader.ABGR);
						int width = TGAReader.getWidth(buffer);
						int height = TGAReader.getHeight(buffer);
						
						Canvas canvas = createImageCanvas(pixels, width, height);
						panel.add(canvas);
					}
					catch(Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	});
	request.send();
}
 
Example #10
Source File: DjVuPage.java    From djvu-html5 with GNU General Public License v2.0 5 votes vote down vote up
private GPixmap decodeJPEG(CachedInputStream iff) throws IOException {
	final GPixmap result = new GPixmap();

	final Image image = new Image();
	final ImageElement imageElement = image.getElement().cast();
	imageElement.getStyle().setProperty("visibility", "hidden");
	Event.setEventListener(imageElement, new EventListener() {
		@Override
		public void onBrowserEvent(Event event) {
			if (Event.ONLOAD == event.getTypeInt()) {
				final int w = imageElement.getWidth(), h = imageElement.getHeight();
				final Canvas canvas = Canvas.createIfSupported();
				canvas.setWidth(w + "px");
				canvas.setCoordinateSpaceWidth(w);
				canvas.setHeight(h + "px");
				canvas.setCoordinateSpaceHeight(h);
				canvas.getContext2d().drawImage(imageElement, 0, 0);

				result.init(h, w, null);
				//TODO result.setImageData(canvas.getContext2d().getImageData(0, 0, w, h));
			}
		}
	});
	
	StringBuilder data = new StringBuilder();
	int b;
	while ((b = iff.read()) != -1) {
		data.append((char) b);
	}
	String dataURL = "data:image/jpeg;base64," + btoa(data.toString());
	image.setUrl(dataURL);

	return result;
}
 
Example #11
Source File: Djvu_html5.java    From djvu-html5 with GNU General Public License v2.0 5 votes vote down vote up
private Widget prepareCanvas() {
	canvas = Canvas.createIfSupported();
	if (canvas == null) {
		// TODO
		throw new RuntimeException("Canvas not supported!");
	}
	canvas.setTabIndex(0);

	final SimplePanel panel = new SimplePanel(canvas);
	panel.setStyleName("content");

	Window.addResizeHandler(e -> resizeCanvas());
	Scheduler.get().scheduleFinally(() -> resizeCanvas());
	return panel;
}
 
Example #12
Source File: TextLayer.java    From djvu-html5 with GNU General Public License v2.0 5 votes vote down vote up
public TextLayer(Djvu_html5 app) {
	this.app = app;
	setStyleName("textLayer");
	getElement().setAttribute("tabindex", "-1");

	addDomHandler(this, ScrollEvent.getType());

	app.getDataStore().addInfoListener(this::pageInfoAvailable);
	if (DjvuContext.getTextLayerEnabled())
		app.getDataStore().addTextListener(this::textAvailable);

	fontMeasure = Canvas.createIfSupported().getContext2d();
}
 
Example #13
Source File: DataStore.java    From djvu-html5 with GNU General Public License v2.0 5 votes vote down vote up
public static CanvasElement createImage(int width, int height) {
	Canvas canvas = Canvas.createIfSupported();
	canvas.setWidth(width + "px");
	canvas.setCoordinateSpaceWidth(width);
	canvas.setHeight(height + "px");
	canvas.setCoordinateSpaceHeight(height);
	return canvas.getCanvasElement();
}
 
Example #14
Source File: TexturedCube.java    From TGAReader with MIT License 4 votes vote down vote up
public void onModuleLoad() {
	
	Canvas canvas = Canvas.createIfSupported();
	canvas.setStyleName("MyCanvas");
	canvas.setCoordinateSpaceWidth(400);
	canvas.setCoordinateSpaceHeight(400);
	RootLayoutPanel.get().add(canvas);
	
	gl = (WebGLRenderingContext)canvas.getContext("experimental-webgl");
	gl.viewport(0, 0, 400, 400);
	
	WebGLBuffer vertexBuffer = gl.createBuffer();
	gl.bindBuffer(ARRAY_BUFFER, vertexBuffer);
	gl.bufferData(ARRAY_BUFFER, Float32Array.create(VERTICES), STATIC_DRAW);

	WebGLShader vertexShader = gl.createShader(VERTEX_SHADER);
	gl.shaderSource(vertexShader, VERTEX_SHADER_SOURCE);
	gl.compileShader(vertexShader);
	
	WebGLShader fragmentShader = gl.createShader(FRAGMENT_SHADER);
	gl.shaderSource(fragmentShader, FRAGMENT_SHADER_SOURCE);
	gl.compileShader(fragmentShader);
	
	program = gl.createProgram();
	gl.attachShader(program, vertexShader);
	gl.attachShader(program, fragmentShader);
	gl.linkProgram(program);
	
	gl.useProgram(program);
	gl.bindBuffer(ARRAY_BUFFER, vertexBuffer);
	
	WebGLUniformLocation texture = gl.getUniformLocation(program, "texture");
	gl.uniform1i(texture, 0);
	
	int posAttr = gl.getAttribLocation(program, "position");
	gl.vertexAttribPointer(posAttr, 3, FLOAT, false, 5*4, 0);
	gl.enableVertexAttribArray(posAttr);
	
	int texAttr = gl.getAttribLocation(program, "texcoord");
	gl.vertexAttribPointer(texAttr, 2, FLOAT, false, 5*4, 3*4);
	gl.enableVertexAttribArray(texAttr);
	
	for(int i=0; i<TEXTURE_URLS.length; i++) {
		loadTexture(TEXTURE_URLS[i], i);
	}
	
}
 
Example #15
Source File: TexturedCube.java    From TGAReader with MIT License 4 votes vote down vote up
void loadTexture(String url, int index) {
	final int i = index;
    XMLHttpRequest request = XMLHttpRequest.create();
    request.open("GET", url);
    request.setResponseType(ResponseType.ArrayBuffer);
    request.setOnReadyStateChange(new ReadyStateChangeHandler() {
        @Override
        public void onReadyStateChange(XMLHttpRequest xhr) {
            if(xhr.getReadyState() == XMLHttpRequest.DONE) {
                if(xhr.getStatus() >= 400) {
                    // error
                    System.out.println("Error");
                }
                else {
                	try {
	                	ArrayBuffer arrayBuffer = xhr.getResponseArrayBuffer();
	    				Uint8ArrayNative u8array = Uint8ArrayNative.create(arrayBuffer);
	    				byte [] buffer = new byte[u8array.length()];
	    				for(int i=0; i<buffer.length; i++) {
	    					buffer[i] = (byte)u8array.get(i);
	    				}
	    				
	    				int [] pixels = TGAReader.read(buffer, TGAReader.ABGR);
	    				int width = TGAReader.getWidth(buffer);
	    				int height = TGAReader.getHeight(buffer);
	    				
	    				Canvas canvas = createImageCanvas(pixels, width, height);
	    				
	    				WebGLTexture texture = gl.createTexture();
	    				gl.enable(TEXTURE_2D);
	    				gl.bindTexture(TEXTURE_2D, texture);
	    				
	    				gl.texImage2D(TEXTURE_2D, 0, RGBA, RGBA, UNSIGNED_BYTE, canvas.getElement());

	    				gl.texParameteri(TEXTURE_2D, TEXTURE_WRAP_S, CLAMP_TO_EDGE);
	    				gl.texParameteri(TEXTURE_2D, TEXTURE_WRAP_T, CLAMP_TO_EDGE);
	    				gl.texParameteri(TEXTURE_2D, TEXTURE_MAG_FILTER, LINEAR);
	    				gl.texParameteri(TEXTURE_2D, TEXTURE_MIN_FILTER, LINEAR);
	    				
	    				textures[i] = texture;
	    				draw();
                	}
                	catch(Exception e) {
                		e.printStackTrace();
                	}
                }
            }
        }
    });
    request.send();
}
 
Example #16
Source File: Djvu_html5.java    From djvu-html5 with GNU General Public License v2.0 4 votes vote down vote up
public Canvas getCanvas() {
	return canvas;
}
 
Example #17
Source File: StructureView.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void drawMolecule(CanvasElement el, JSMolecule mol, int displayMode, String[] atomText) {
    Canvas canvas = Canvas.wrap(el);
    Context2d ctx = canvas.getContext2d();
    drawMolecule(ctx, mol.getStereoMolecule(), canvas.getCoordinateSpaceWidth(), canvas.getCoordinateSpaceHeight(),
            displayMode, atomText);
}
 
Example #18
Source File: AbstractESRPane.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void draw(Canvas toolBar) {
  Context2d context2d = toolBar.getContext2d();
  drawButtons(new GraphicsContext(context2d));
}
 
Example #19
Source File: MaterialCameraCapture.java    From gwt-material-addins with Apache License 2.0 4 votes vote down vote up
@Override
public String captureToDataURL(String mimeType) {
    return nativeCaptureToDataURL(Canvas.createIfSupported().getCanvasElement(), video.getElement(), mimeType);
}
 
Example #20
Source File: ToolBarImpl.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void draw(Canvas toolBar) {
  Context2d context2d = toolBar.getContext2d();
  GraphicsContext ctx = new GraphicsContext(context2d);
  drawButtons(ctx);
  drawESRButtons(ctx);
}
 
Example #21
Source File: CirSim.java    From circuitjs1 with GNU General Public License v2.0 4 votes vote down vote up
public Canvas getCircuitAsCanvas(boolean print) {
    	// create canvas to draw circuit into
    	Canvas cv = Canvas.createIfSupported();
    	Rectangle bounds = getCircuitBounds();
    	
	// add some space on edges because bounds calculation is not perfect
    	int wmargin = 140;
    	int hmargin = 100;
    	int w = (bounds.width+wmargin) ;
    	int h = (bounds.height+hmargin) ;
    	cv.setCoordinateSpaceWidth(w);
    	cv.setCoordinateSpaceHeight(h);
    	double oldTransform[] = Arrays.copyOf(transform, 6);
    
	Context2d context = cv.getContext2d();
	Graphics g = new Graphics(context);
	context.setTransform(1, 0, 0, 1, 0, 0);
        
        double scale = 1;
        
	// turn on white background, turn off current display
	boolean p = printableCheckItem.getState();
	boolean c = dotsCheckItem.getState();
	if (print)
	    printableCheckItem.setState(true);
        if (printableCheckItem.getState()) {
            CircuitElm.whiteColor = Color.black;
            CircuitElm.lightGrayColor = Color.black;
            g.setColor(Color.white);
        } else {
            CircuitElm.whiteColor = Color.white;
            CircuitElm.lightGrayColor = Color.lightGray;
            g.setColor(Color.black);
            g.fillRect(0, 0, g.context.getCanvas().getWidth(), g.context.getCanvas().getHeight());
        }
	dotsCheckItem.setState(false);

        if (bounds != null)
            scale = Math.min(w /(double)(bounds.width+wmargin),
                             h/(double)(bounds.height+hmargin));
        scale = Math.min(scale, 1.5); // Limit scale so we don't create enormous circuits in big windows
        
        // ScopeElms need the transform array to be updated
	transform[0] = transform[3] = scale;
	transform[4] = -(bounds.x-wmargin/2);
	transform[5] = -(bounds.y-hmargin/2);
	context.scale(scale, scale);
	context.translate(transform[4], transform[5]);
	
	// draw elements
	int i;
	for (i = 0; i != elmList.size(); i++) {
	    getElm(i).draw(g);
	}
	
	// restore everything
	printableCheckItem.setState(p);
	dotsCheckItem.setState(c);
	transform = oldTransform;
	return cv;
}
 
Example #22
Source File: TextMetricsCalculator.java    From jetpad-projectional-open-source with Apache License 2.0 4 votes vote down vote up
static double calculateWidth(Font font, String text) {
  Canvas canvas = canvas();
  Context2d ctx = canvas.getContext2d();
  ctx.setFont(getFontString(font));
  return ctx.measureText(normalize(text)).getWidth();
}
 
Example #23
Source File: CirSim.java    From circuitjs1 with GNU General Public License v2.0 4 votes vote down vote up
void doPrint() {
    Canvas cv = getCircuitAsCanvas(true);
    printCanvas(cv.getCanvasElement());
}
 
Example #24
Source File: Util.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
public static Canvas createScaledCanvas(int width, int height) {
  Canvas canvas = Canvas.createIfSupported();
  
  scaleCanvas(canvas, width, height);

  return canvas;
}