javascript - 动态创建 Canvas 并设置宽度和高度时字体太小

标签 javascript html canvas

如何为 Canvas 中绘制的图像设置正确的字体大小?前两个显示扭曲的文本。第三个是我需要的结果。真的不知道我在这里缺少什么。

html:

<div id="wrap1"></div>
<canvas id="wrap2"></canvas>
<canvas id="wrap3" width="100" height="100" style="border:1px solid;></canvas>

JavaScript:

    function createImg(){
        var wrap=document.getElementById("wrap1");
        wrap.innerHTML="";
        var c = document.createElement('canvas');
        document.body.appendChild(c);
        wrap.appendChild(c);
        c.style.border = '1px solid #333';
        c.style.width = '100px';
        c.style.height = '100px';
        var ctx=c.getContext("2d");
        ctx.font="24px Arial";
        ctx.fillText("Hello World",50,50);
    }
    createImg();
    function createImg2(){
        var c=document.getElementById("wrap2");
        c.style.border = '1px solid #333';
        c.style.width = '100px';
        c.style.height = '100px';
        var ctx=c.getContext("2d");
        ctx.font="24px Arial";
        ctx.fillText("Hello World",50,50);
    }
    createImg2();
    function createImg3(){
        var c=document.getElementById("wrap3");
        var ctx=c.getContext("2d");
        ctx.font="16px 'Source Sans Pro', sans-serif";
        ctx.fillText("Hello World",10,50);
        ctx.textAlign = 'center';
    }
    createImg3();

非常感谢任何可以帮助我的人!

jsfiddle

最佳答案

不要使用 CSS 调整 Canvas 大小。相反,调整 Canvas 元素本身的大小:

当您使用 CSS 时,您只是拉伸(stretch)/压缩自然的 300px X 100px Canvas 尺寸。

当您调整 Canvas 元素本身的大小时,您将添加或删除像素,但不会拉伸(stretch)/压缩任何像素。

// not  c.style.width = '100px'; c.style.height = '100px';
canvas.width=100;
canvas.height=100;

关于javascript - 动态创建 Canvas 并设置宽度和高度时字体太小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418502/

相关文章:

javascript - {名称: value} notation for arrays in Javascript

javascript - 如何通过 JavaScript 计算 HTML 正文中的选定单词

javascript - 检查 Ember 应用程序中的 ReadyState

c++ - 需要 C++ HTML 解析器 + 正则表达式支持

javascript - 在 ng-repeat 生成的 <ul> 列表中使用 ng-model

android - 如何使用 android.graphics.Camera.rotateX(angle) 在特定点旋转 Canvas

javascript - 数组中有很多 null 值意味着有什么坏处吗?

html - 溢出自动容器内的元素没有正确的宽度(所有组合的子元素)

android - drawBitmapMesh 如何在 android canvas 中工作

javascript - 为什么我的 requestAnimFrame 仍然很慢?