简体   繁体   中英

Font size too small when dynamically creating canvas and setting width and height

How can i set the correct font-size to the image drawn in canvas? The first two shows distorted text. The third one is the result i need. Dont really know what I'm missing here.

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

Big thank you for anyone who can help me!

jsfiddle

Don't resize the canvas using CSS. Instead resize the canvas element itself:

When you use CSS, you are just stretching/compressing the natural 300px X 100px canvas size.

When you resize the canvas element itself, you are adding or removing pixels, but not stretching/compressing any pixels.

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

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