'JS/TS proper structuring: canvas drawing from class, without class "knowing" about the canvas

I have a parent class, that has a <canvas> and a tool property.
(written in Typescript):

class CanvasHandler {
    canvas: HTMLCanvasElement;
    tool: Tool;

    constructor(canvas: HTMLCanvasElement, tool: Tool) {
        this.canvas = canvas;
        this.tool = tool;
    }
}

The tool is going to be an instance of the class Pen, that extends Tool:

interface IPen {
    size: number;
    color: string;
}

class Pen extends Tool implements IPen {
    size: number;
    color: string;

    constructor(size: number, color: string) {
        super(ToolNames.PEN, ToolDescriptions.PEN);

        this.size = size;
        this.color = color;
    }

    override onMouseMove(event: Event) {
       // DRAW CIRCLE TO CANVAS
    }

}

I have implemented an Observer on the <canvas>-Element, so now every time the mouse moves over the canvas, the method onMouseMove of CanvasHandler.tool gets executed. Now, every time the onMouseMove function gets called, I want to draw a circle to the <canvas>. I could provide a reference to the <canvas>, so that the class Tool "knows" the <canvas>, and ´onMouseMove´ I could override the drawing behaviour in Pen. However I wonder, if theres not a better way, to relocate the drawing functionality, so that the class Pen and Tool dont directly "know" about the <canvas> element.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source