HTML 5 canvas字体被忽略 [英] HTML 5 canvas font being ignored

查看:359
本文介绍了HTML 5 canvas字体被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一些文本到canvas元素,但似乎我放入的字体选项被完全忽略。无论我改变他们,它都出来是一样的,我相信是默认的10px sans-serif。

  function start()
{
canvas = document.getElementById('c');
ctx = canvas.getContext('2d');
ctx.fillStyle =white;
ctx.font =12px monospace;
ctx.textBaseline =top;
}

它不能在Firefox或Chrome中使用。

解决方案

事实证明,需要使用 ctx.font 在同一个函数中执行 fillText()



这使它像一个charm一样工作。


$ b 他的评论,这个答案是错误的。您的上下文需要使用 ctx.save() ctx.restore()保存和恢复当您再次调用canvas.getContext('2d')时重置。


I'm trying to write some text to a canvas element, but it seems that the font options I put in are being completely ignored. No matter what I change them to, it all comes out the same, which I believe to be the default 10px sans-serif. Heres what I have (this function runs on load)

function start()
{
    canvas = document.getElementById('c');
    ctx = canvas.getContext('2d');
    ctx.fillStyle = "white";
    ctx.font = "12px monospace";
    ctx.textBaseline = "top";
}

It doesn't work in either Firefox or Chrome.

解决方案

As it turns out, the ctx.font change needs to be used in the same function that is doing the fillText()

This makes it work like a charm.

EDIT

As richtaur mentioned in his comment, this answer is wrong. Your context needs to be saved and restored using ctx.save() and ctx.restore() as it currently gets reset when you call canvas.getContext('2d') again.

这篇关于HTML 5 canvas字体被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆