Skip to content

Instantly share code, notes, and snippets.

@Splaktar
Last active December 27, 2015 17:19
Show Gist options
  • Save Splaktar/7361558 to your computer and use it in GitHub Desktop.
Save Splaktar/7361558 to your computer and use it in GitHub Desktop.
Quick example of how to draw a pie chart on an HTML5 canvas with GWT. It uses hard coded values. For real use, you would want to pass those percentages into the method.
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.CssColor;
import com.google.gwt.core.client.GWT;
private void drawChart()
{
// Initialize the canvas.
final Canvas canvas = Canvas.createIfSupported();
if (canvas != null)
{
canvas.setCoordinateSpaceHeight(300);
canvas.setCoordinateSpaceWidth(300);
canvas.setPixelSize(300, 300);
// Get the dimensions of the canvas.
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);
// Draw a filled arc.
context.setFillStyle(CssColor.make(255, 211, 25));
context.beginPath();
context.moveTo(cx, cy);
context.arc(cx, cy, radius, 0, Math.PI * 0.15);
context.fill();
context.setFillStyle(CssColor.make(255, 0, 25));
context.beginPath();
context.moveTo(cx, cy);
context.arc(cx, cy, radius, Math.PI * 0.15, Math.PI * 0.45);
context.fill();
context.setFillStyle(CssColor.make(0, 220, 200));
context.beginPath();
context.moveTo(cx, cy);
context.arc(cx, cy, radius, Math.PI * 0.45, Math.PI * 0.5);
context.fill();
context.setFillStyle(CssColor.make(25, 255, 25));
context.beginPath();
context.moveTo(cx, cy);
context.arc(cx, cy, radius, Math.PI * 0.5, Math.PI * 1.2);
context.fill();
context.setFillStyle(CssColor.make(25, 0, 255));
context.beginPath();
context.moveTo(cx, cy);
context.arc(cx, cy, radius, Math.PI * 1.2, Math.PI * 2);
context.fill();
graphPanel.add(canvas);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment