Writing text to the canvas via a JavaScript function

65
December 20, 2018, at 11:40 AM

I understand how to get text onto a canvas in JavaScript outside of a function, but putting the code in a function seems to break everything

Example:

var c = document.getElementById("APICanvas");
var canvas = c.getContext("2d");
canvas.font('20px Times New Roman);
canvas.fillText("Hello, world!", 20, 20);

This results in "Hello, world!" at (20,20) on the canvas, but

function text(text,x,y) {
    var c = document.getElementById("APICanvas");
            var canvas = c.getContext("2d");
            canvas.font('20px Times New Roman);
            canvas.fillText(text,x,y);
    }
text("Hello, world!",20,20);

This results in nothing showing up on the canvas.

I don't know why using this inside a function doesn't work and am seriously confused.

Answer 1

font is a property not function. You have to set the property with assignment operator. You have also missed the closing ' at the end of the property string value.

Change

canvas.font('20px Times New Roman);

To

canvas.font = '20px Times New Roman';

function text(text,x,y) { 
  var c = document.getElementById("APICanvas"); 
  var canvas = c.getContext("2d"); 
  canvas.font = '20px Times New Roman'; 
  canvas.fillText(text,x,y); 
} 
 
text("Hello, world!",20,20);
<canvas id="APICanvas"></div>

READ ALSO
Linking to Event from the Google Calendar API

Linking to Event from the Google Calendar API

I'm trying to create an external link from my web app to a google calendar eventFrom the Google::Apis::CalendarV3::Event that I receive with this API, I get https://www

25
Assigning false returns undefined

Assigning false returns undefined

the following code is outputting "undefined" but when x is true, it worksIf I assign string 'false' it is correct

34
Mortage Interest Rate Calculator Returning Ridiculous Values

Mortage Interest Rate Calculator Returning Ridiculous Values

The code is returning extremely low values for a mortgage payment

56
SQLIntegrityConstraintViolationException when creating new Insertion into database JPA

SQLIntegrityConstraintViolationException when creating new Insertion into database JPA

I have a Controller ProjectContoller that is supposed to receive a ProjectDto and save this into my database

58