如何在画布中放置文本的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>
答案 0 :(得分:0)
这样的问题总是归结为规模问题。您试图将CSS中的像素值与画布的像素值进行匹配。
当画布宽度和高度设置为与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>
调整比例时,请转到正确的尺寸