2016-02-24 26 views
0

如何將像素中的文本的lineWidth放置在畫布中。如何將canvas中的文本的lineWidth屬性以像素爲單位?

每當我把ctx.lineWidth = 3px;整個文本都是空白的。只有當ctx.lineWidth = 3;它在腳本中起作用。而當它的3這意味着3像素或其他單位?

<body> 
    <canvas id="c" width="800" height="800"></canvas> 
    <script> 

    var c = document.querySelector("#c"); 
    var ctx = c.getContext("2d"); 
    ctx.strokeStyle = "Black"; 
    ctx.fill(); 
    ctx.font = "bold 36pt impact"; 
    ctx.lineWidth = 3; // here is the problem. I want to use pixels 
    //ctx.lineWidth = 3px; // it goes blank if I use this 
    ctx.strokeText("Hello Hello!", 50, 50); 

    //image.src = "http://www.wired.com/images_blogs/underwire/2010/06/fry_660.jpg"; 
    </script> 
</body> 
+1

是,'context.lineWidth'需要的像素值 - 不需要指定'px'。 :-) – markE

回答

0

這樣的問題總是歸結爲規模問題。您正嘗試將CS​​S中的像素值與畫布的像素值相匹配。

問題出現在畫布寬度和高度設置爲與clientWidth/clientHeight不同的值時。

var c = document.querySelector("#c"); 
 
    var ctx = c.getContext("2d"); 
 
    
 
    var textSize = 36 
 
    ctx.strokeStyle = "Black"; 
 
    ctx.fill(); 
 
    ctx.font = "bold " + textSize + "px impact"; 
 
    ctx.lineWidth = 3; // here is the problem. I want to use pixels 
 
    //ctx.lineWidth = 3px; // it goes blank if I use this 
 
    ctx.strokeText("Hello Hello! (36px)", 50, 50); 
 

 
    var scale = c.clientWidth/c.width; 
 
    ctx.strokeStyle = "Black"; 
 
    ctx.fill(); 
 
    ctx.font = "bold " + textSize/scale + "px impact"; 
 
    ctx.lineWidth = 3; // here is the problem. I want to use pixels 
 
    //ctx.lineWidth = 3px; // it goes blank if I use this 
 
    ctx.strokeText("Hello Hello! (36px * scale)", 50, 200); 
 

 
    //image.src = "http://www.wired.com/images_blogs/underwire/2010/06/fry_660.jpg";
<body style="width: 400px"> 
 
    <div style="font-size: 36px; font-weight: bold; font-family: impact">Hello Hello (css)</div> 
 
    <canvas id="c" style="width: 100%" width="800" height="800"></canvas> 
 
</body>

當你調整的規模去正確的大小

相關問題