<html>
<head>
<title>canvas绘制的文字如何换行</title>
<style type="text/css">
</style>
</head>
<body>
<canvas id="canvas" height="400" width="400"></canvas>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script>
$(function() {
var myAction = {};
$.extend(myAction, {
drawText: function(t, x, y, w) {
var c = document.getElementById("canvas");
var context = c.getContext("2d");
var chr = t.split("");
var temp = "";
var row = [];
context.font = "20px Arial";
context.fillStyle = "black";
context.textBaseline = "middle";
for (var a = 0; a < chr.length; a++) {
if (context.measureText(temp).width < w) {;
} else {
row.push(temp);
temp = "";
}
temp += chr[a];
}
row.push(temp);
for (var b = 0; b < row.length; b++) {
context.fillText(row[b], x, y + (b + 1) * 20);
}
},
initData: function() {
myAction.drawText("Hello, World!What a nice day.", 0, 0, 110);
}
})
var init = function() {
myAction.initData();
}();
});
</script>
</body>
</html>