Open david2tdw opened 4 years ago
文字内容超出,也可以通过缩放文字来解决:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>JS Bin</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
<script>
var canvas = document.getElementById('myCanvas')
var canvasWidth = canvas.width
var context = canvas.getContext('2d')
var x = 0
var y = 400
var text = 'Hello World1234222222222'
context.font = '500px 微软雅黑'
var textWidth = context.measureText(text).width
if (textWidth > canvasWidth) {
var scaled = canvasWidth / textWidth
context.scale(scaled, scaled)
}
//x,y用于居中,文字起始点,和对齐有关。
context.fillText(text, x, y)
</script>
绘制图片的x,y坐标是从图片的 左上角 开始计算位置的。 context.fillText(text, x, y) 绘制文字的x,y坐标是从文字的 右下角 开始计算位置的。