Read the original article:DrawingRenderingContext draws an image how the graphics are filled in?
Context
When drawing an image using DrawingRenderingContext, the image defaults to solid black, how to change the fill color or border color of the drawn image?
Description
Use DrawingRenderingContext to realize pattern drawing on Canvas
Most geometric shapes and text can be drawn with either a brush or a paintbrush. The brush can be used to draw frames, the brush can be used to draw solid shapes, or a combination of the two can be used to draw solid shapes with strokes.
Solution
If you want to use DrawingRenderingContext to draw a non-default solid pattern and achieve the fill effect you want, you can set the Canvas's Pen and Brush to draw graphics to achieve the fill effect.
- Draw the graphic box: Set the brush style and use attachpen to apply the brush to the canvas drawing, the key code is as follows:
const canvas = this.context.canvas;
let pen = new drawing.Pen();
pen.setColor(255, 255, 0, 0)
pen.setStrokeWidth(4)
canvas.attachPen(pen)
const font = new drawing.Font();
font.setSize(150);
const textBlob =
drawing.TextBlob.makeFromString('Hello World!',font, drawing.TextEncoding.TEXT_ENCODING_UTF8);
canvas.drawTextBlob(textBlob,0,200)
this.context.invalidate()
- Draw solid shapes: Set the brush style and use attachbrush to apply the brush to the canvas drawing, the key code is as follows:
const canvas = this.context.canvas;
let pen = new drawing.Pen();
pen.setColor(255, 0, 0, 255)
canvas.drawCircle(600 / 2, 600 / 2, Math.min(400, 400) / 2)
this.context.invalidate()
- Drawing solid shapes with strokes: Both strokes and fills, applying both brush and brush styles to the canvas drawing, the key code is as follows:
console.info(getContext().filesDir)
const canvas = this.context.canvas;
const pen = new drawing.Pen();
pen.setColor(255, 255, 0, 0)
pen.setStrokeWidth(4)
let brush = new drawing.Brush()
brush.setColor(255, 255, 0, 0)
canvas.attachBrush(brush)
canvas.drawCircle(600 / 2, 600 / 2, Math.min(400, 400) / 2)
let brush = new drawing.Brush()
brush.setColor(255, 255, 255, 0)
canvas.attachBrush(brush)
canvas.drawCircle(600 / 2, 600 / 2, Math.min(200, 200) / 2)
this.context.invalidate()
Key Takeaways
- To change the fill and border colors of shapes drawn on a Canvas using
DrawingRenderingContext, you must usePenandBrushobjects. - The
Penobject is used to set the color and style for drawing borders or strokes, while theBrushobject is used for filling solid shapes. -
To draw a border, create a
Penobject, set its color and stroke width, and apply it to the canvas withcanvas.attachPen(). -
To draw a solid shape, create a
Brushobject, set its color, and apply it to the canvas withcanvas.attachBrush(). -
To draw a solid shape with a border, you can attach both a
Penand aBrushto the canvas before drawing the shape. - After drawing, you must call
this.context.invalidate()to refresh the canvas and display the changes.



Top comments (0)