1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width">
- <title>canvas 高清文字</title>
- </head>
- <body>
- <script>
-
- function convertToRGBAStr(color, opacity=1){
- return "rgba(" + color.r + "," + color.g + "," + color.b + "," + opacity + ")";
- }
- function roundRect(ctx, x, y, w, h, r)
- {
- ctx.beginPath();
- ctx.moveTo(x+r, y);
- ctx.lineTo(x+w-r, y);
- ctx.quadraticCurveTo(x+w, y, x+w, y+r);
- ctx.lineTo(x+w, y+h-r);
- ctx.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
- ctx.lineTo(x+r, y+h);
- ctx.quadraticCurveTo(x, y+h, x, y+h-r);
- ctx.lineTo(x, y+r);
- ctx.quadraticCurveTo(x, y, x+r, y);
- ctx.closePath();
- ctx.fill();
- ctx.stroke();
- }
- function canvasText(text, _c){
- var canvas = document.createElement('canvas');
- var context = canvas.getContext('2d');
- var dpr = window.devicePixelRatio || window.webkitDevicePixelRatio || window.mozDevicePixelRatio || 1;
- var borderColor = _c.borderColor;
- var backgroundColor = _c.backgroundColor;
- var textColor = _c.textColor;
- context.font = "" + _c.fontSize + "px " + _c.fontFace;
- var metrics = context.measureText(text);
- var textWidth = metrics.width;
-
- /*计算画布的高度*/
- var h = Math.round(_c.lineHeight * _c.fontSize + _c.borderThickness * 2);
- /*计算画布的宽度*/
- var w = Math.round(_c.borderThickness * 2 + textWidth + _c.padding * 2);
- canvas.width = dpr * w;
- canvas.height = dpr * h;
- canvas.style.width = w + 'px';
- canvas.style.height = h + 'px';
- // context.scale(dpr, dpr);
- context.font = "" + _c.fontSize + "px " + _c.fontFace;
- context.fillStyle = convertToRGBAStr(backgroundColor, _c.opacity);
- context.strokeStyle = convertToRGBAStr(borderColor, _c.opacity);
- context.lineWidth = _c.borderThickness;
- roundRect(context, _c.borderThickness/2, _c.borderThickness/2, w - _c.borderThickness , h- _c.borderThickness, _c.borderRadius);
- context.textAlign = 'center';
- context.textBaseline = 'middle';
- context.fillStyle = convertToRGBAStr(textColor);
- context.fillText(text, w/2, h/2);
- return canvas;
- }
- var canvas = canvasText('测试高清文字',{
- fontFace: "Arial",
- fontSize: 28,
- borderThickness: 1,
- borderRadius:4,
- padding: 40,
- lineHeight: 2,
- borderColor: {r:255,g:0,b:0},
- backgroundColor: {r:255,g:0,b:0},
- textColor: {r:255,g:255,b:255},
- opacity: 1.0,
- })
- document.body.append(canvas);
- </script>
- </body>
- </html>
|