wmash
wmash

Reputation: 4202

Set HTML canvas context via object

Up until now, I have set HTML canvas context the way in tutorials it is shown, like:

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

ctx.font = "15px calibri";
...

I was wondering whether it is possible to set the context of the canvas by passing in an object with the correct attributes to one of it's methods? For example:

var canvas = document.getElementById("canvas");


var context = {
    font: "15px calibri",
    ...
);

canvas.setContext(context);

The reason for this is I am creating a custom canvas in angular. For example, my controller will get the <canvas> element. A method in a service will callback the context object to set for the canvas.

The custom canvas is to be converted to PNG and set as the icon for a Marker on Google Maps. The marker is added to the maps in the service:

addMarkerToMap: function(position, map, canvas) {
    new google.maps.Marker({
        position: position,
        map: map,
        icon: canvas.toDataURL("image/png")
    });
}

So I am hoping to pass in the canvas element into this fucntion (with it's context already set) and just set it's PNG equivalent as the Marker icon.

EDIT:

I've now realised that other then just setting attributes (i.e. fillStyle), I am invoking the contexts methods (i.e. beginPath()).
I think that this will make it much harder to accomplish what I am trying

Upvotes: 7

Views: 4318

Answers (2)

Nick Louloudakis
Nick Louloudakis

Reputation: 6005

Based on this answer - and the spec as it says, you possibly cannot replace the canvas context with another, as "Every canvas has what is called a primary context".

If possible, you could create a canvas programmatically and then append it to HTML as a child (or even cloning & replacing the old one at cases - if not too many replacements happening).

You could for instance use jQuery to do something like:

// Just a new canvas, you could even clone the old one
var canvas1 = $('<canvas/>', {
  id: 'canvas1',
  height: 500,
  width: 200,
  font: '15 px'
});
document.body.appendChild(canvas1);

Upvotes: 2

rishat
rishat

Reputation: 8376

Even though it looks like nonsence, after you mutate context of a canvas element, it is preserved:

const canvas1 = document.getElementById('myCanvas');
const ctx = canvas1.getContext('2d');

ctx.font = '15px Calibri';

const canvas2 = document.getElementById('myCanvas');
console.log(canvas2.getContext('2d').font); // -> "15px Calibri"

So, in you case, it is safe to rely on context at any moment in future after you pass reference to canvas element to addMarkerToMap function.

Upvotes: 2

Related Questions