diff --git a/src/CanvasRenderingContext2d.cc b/src/CanvasRenderingContext2d.cc index 33314b5..bfc51de 100644 --- a/src/CanvasRenderingContext2d.cc +++ b/src/CanvasRenderingContext2d.cc @@ -89,6 +89,7 @@ Context2d::Initialize(Handle target) { NODE_SET_PROTOTYPE_METHOD(t, "clearRect", ClearRect); NODE_SET_PROTOTYPE_METHOD(t, "rect", Rect); NODE_SET_PROTOTYPE_METHOD(t, "setTextPath", SetTextPath); + NODE_SET_PROTOTYPE_METHOD(t, "measureText", MeasureText); NODE_SET_PROTOTYPE_METHOD(t, "moveTo", MoveTo); NODE_SET_PROTOTYPE_METHOD(t, "lineTo", LineTo); NODE_SET_PROTOTYPE_METHOD(t, "bezierCurveTo", BezierCurveTo); @@ -843,6 +844,28 @@ Context2d::SetFont(const Arguments &args) { return Undefined(); } +/* + * Return the given text extents. + */ + +Handle +Context2d::MeasureText(const Arguments &args) { + HandleScope scope; + + Context2d *context = ObjectWrap::Unwrap(args.This()); + cairo_t *ctx = context->getContext(); + + String::Utf8Value str(args[0]->ToString()); + Local obj = Object::New(); + + cairo_text_extents_t te; + cairo_text_extents(ctx, *str, &te); + obj->Set(String::New("width"), Number::New(te.width)); + obj->Set(String::New("height"), Number::New(te.height)); + + return scope.Close(obj); +} + /* * Set text path at x, y. */ diff --git a/src/CanvasRenderingContext2d.h b/src/CanvasRenderingContext2d.h index 8f5bb9b..077bf7c 100644 --- a/src/CanvasRenderingContext2d.h +++ b/src/CanvasRenderingContext2d.h @@ -65,6 +65,7 @@ class Context2d: public node::ObjectWrap { static Handle SetFillPattern(const Arguments &args); static Handle SetStrokePattern(const Arguments &args); static Handle SetTextPath(const Arguments &args); + static Handle MeasureText(const Arguments &args); static Handle BezierCurveTo(const Arguments &args); static Handle QuadraticCurveTo(const Arguments &args); static Handle LineTo(const Arguments &args); diff --git a/test/canvas.test.js b/test/canvas.test.js index a381792..d6fbc9d 100644 --- a/test/canvas.test.js +++ b/test/canvas.test.js @@ -747,6 +747,16 @@ module.exports = { , 'Context2d#strokeText()'); }, + 'test Context2d#measureText()': function(assert){ + var canvas = new Canvas(200, 200) + , ctx = canvas.getContext('2d'); + + ctx.font = 'normal 40px Impact'; + assert.eql({ width: 111, height: 32 }, ctx.measureText('Wahoo')); + assert.eql(ctx.measureText(123), ctx.measureText('123')); + assert.eql(ctx.measureText(), ctx.measureText('undefined')); + }, + 'test Canvas#toBuffer()': function(assert){ assert.ok(Buffer.isBuffer(new Canvas(200, 200).toBuffer()), 'Canvas#toBuffer() failed'); },