简体   繁体   中英

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 (ie fillStyle ), I am invoking the contexts methods (ie beginPath() ).
I think that this will make it much harder to accomplish what I am trying

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM