cavans 文字换行
1.cavans计算及逐字计算
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>cavans 文字换行</title> </head> <body> <canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;"> 您的浏览器不支持 HTML5 canvas 标签。 </canvas> <script> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.font="20px Georgia"; ctx.fillText("一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十",10,50); ctx.font="30px Verdana"; // 创建一个渐变 var gradient=ctx.createLinearGradient(0,0,c.width,0); gradient.addColorStop("0","magenta"); gradient.addColorStop("0.5","blue"); gradient.addColorStop("1.0","red"); // 填充一个渐变 ctx.fillStyle=gradient; console.log(ctx) CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) { if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') { return; } var context = this; var canvas = context.canvas; if (typeof maxWidth == 'undefined') { maxWidth = (canvas && canvas.width) || 300; } if (typeof lineHeight == 'undefined') { lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) || parseInt(window.getComputedStyle(document.body).lineHeight); } // 字符分隔为数组 var arrText = text.split(''); var line = ''; for (var n = 0; n < arrText.length; n++) { var testLine = line + arrText[n]; var metrics = context.measureText(testLine); var testWidth = metrics.width; if (testWidth + x > maxWidth && n > 0) { context.fillText(line, x, y); line = arrText[n]; y += lineHeight; } else { line = testLine; } } context.fillText(line, x, y); }; console.log(ctx) ctx.wrapText('一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十', 50, 100, 300, 30) </script> </body> </html>