Getting the canvas to draw on top of it

Hi, I want to draw some small marks on the screen, and I thought it was possible to get the canvas, use the getContext() method and draw directily with fillRect() for instance.

This is the code:

var canvas =;
var canvasWidth = parseInt(canvas.clientWidth, 10);
var canvasHeight = parseInt(canvas.clientHeight, 10);

var ctx = canvas.getContext("2d");
ctx.fillStyle = "#00FF1D";

However, ctx is NULL.
Does anyone know what I am doing wrong??
Thanks in advance.

I have the same question. I want to draw some lines on the HTML canvas. Is it possible to get the 2d Context this way?
For context, I am trying to draw a dashed line in Playcanvas App. I can take the mesh route specified here, but I need to constantly keep scaling the mesh and I don’t know of any way how I can maintain the texel density while scaling the object (The way I know would be computationally expensive)

I am using the new drawLines API but it doesn’t seem to have options for drawing dashed lines either.

Here is the test project I am playing around in:

Any help would be appreciated :slight_smile:

My guess is, this is the reason getContext(“2d”) returns null

I think I found a solution. But would like to know if anyone thinks this could have a huge impact on the performance (specially if I draw multiple of these dashedLines on the same canvas)

Sample project here:
In case anyone is looking for the same solution in the future :slight_smile:

var DrawDashedLines = pc.createScript('drawDashedLines');

DrawDashedLines.attributes.add("startPoint", {"type": "entity"});
DrawDashedLines.attributes.add("endPoint", {"type": "entity"});

var ctx;

// initialize code called once per entity
DrawDashedLines.prototype.initialize = function() 
    SCENE_CAMERA ="SceneCamera").camera;
    this.screenStartPosition = new pc.Vec2();
    this.screenEndPosition = new pc.Vec2();
    this.drawDashedLine([10, 10], 0, 0, 300, 300);

DrawDashedLines.prototype.update = function() 
    this.dimensionsCanvas.width =;
    this.dimensionsCanvas.height =;
    SCENE_CAMERA.worldToScreen(this.startPoint.getPosition(), this.screenStartPosition);
    SCENE_CAMERA.worldToScreen(this.endPoint.getPosition(), this.screenEndPosition);

    this.drawDashedLine([10, 10], this.screenStartPosition.x, this.screenStartPosition.y, this.screenEndPosition.x, this.screenEndPosition.y);

DrawDashedLines.prototype.createDimensionsCanvas = function() 
    this.dimensionsCanvas = document.createElement('canvas'); = "dimensionLinesCanvas";
    this.dimensionsCanvas.width =;
    this.dimensionsCanvas.height =; = "absolute";
    ctx = this.dimensionsCanvas.getContext('2d');

DrawDashedLines.prototype.drawDashedLine = function(pattern, startX, startY, endX, endY)
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.strokeStyle = '#ff0000';

1 Like