直播数据中心

ceshi.html 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width">
  6. <title>canvas 高清文字</title>
  7. </head>
  8. <body>
  9. <script>
  10. function convertToRGBAStr(color, opacity=1){
  11. return "rgba(" + color.r + "," + color.g + "," + color.b + "," + opacity + ")";
  12. }
  13. function roundRect(ctx, x, y, w, h, r)
  14. {
  15. ctx.beginPath();
  16. ctx.moveTo(x+r, y);
  17. ctx.lineTo(x+w-r, y);
  18. ctx.quadraticCurveTo(x+w, y, x+w, y+r);
  19. ctx.lineTo(x+w, y+h-r);
  20. ctx.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
  21. ctx.lineTo(x+r, y+h);
  22. ctx.quadraticCurveTo(x, y+h, x, y+h-r);
  23. ctx.lineTo(x, y+r);
  24. ctx.quadraticCurveTo(x, y, x+r, y);
  25. ctx.closePath();
  26. ctx.fill();
  27. ctx.stroke();
  28. }
  29. function canvasText(text, _c){
  30. var canvas = document.createElement('canvas');
  31. var context = canvas.getContext('2d');
  32. var dpr = window.devicePixelRatio || window.webkitDevicePixelRatio || window.mozDevicePixelRatio || 1;
  33. var borderColor = _c.borderColor;
  34. var backgroundColor = _c.backgroundColor;
  35. var textColor = _c.textColor;
  36. context.font = "" + _c.fontSize + "px " + _c.fontFace;
  37. var metrics = context.measureText(text);
  38. var textWidth = metrics.width;
  39. /*计算画布的高度*/
  40. var h = Math.round(_c.lineHeight * _c.fontSize + _c.borderThickness * 2);
  41. /*计算画布的宽度*/
  42. var w = Math.round(_c.borderThickness * 2 + textWidth + _c.padding * 2);
  43. canvas.width = dpr * w;
  44. canvas.height = dpr * h;
  45. canvas.style.width = w + 'px';
  46. canvas.style.height = h + 'px';
  47. // context.scale(dpr, dpr);
  48. context.font = "" + _c.fontSize + "px " + _c.fontFace;
  49. context.fillStyle = convertToRGBAStr(backgroundColor, _c.opacity);
  50. context.strokeStyle = convertToRGBAStr(borderColor, _c.opacity);
  51. context.lineWidth = _c.borderThickness;
  52. roundRect(context, _c.borderThickness/2, _c.borderThickness/2, w - _c.borderThickness , h- _c.borderThickness, _c.borderRadius);
  53. context.textAlign = 'center';
  54. context.textBaseline = 'middle';
  55. context.fillStyle = convertToRGBAStr(textColor);
  56. context.fillText(text, w/2, h/2);
  57. return canvas;
  58. }
  59. var canvas = canvasText('测试高清文字',{
  60. fontFace: "Arial",
  61. fontSize: 28,
  62. borderThickness: 1,
  63. borderRadius:4,
  64. padding: 40,
  65. lineHeight: 2,
  66. borderColor: {r:255,g:0,b:0},
  67. backgroundColor: {r:255,g:0,b:0},
  68. textColor: {r:255,g:255,b:255},
  69. opacity: 1.0,
  70. })
  71. document.body.append(canvas);
  72. </script>
  73. </body>
  74. </html>