简体   繁体   中英

Writing text to the canvas via a JavaScript function

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.

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> 

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