湘妃到家前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.8 KiB

1 month ago
  1. function drawTextVertical(context, text, x, y,totalHeight) {
  2. var arrText = text.split('');
  3. var arrWidth = arrText.map(function (letter) {
  4. //totalHeight总高度,用于计算每个字之间的间距
  5. if(arrText.length > 3){ //这里这么写只是解决bug快,不想改生成海报那边了
  6. return totalHeight / (arrText.length - 1);
  7. }else{
  8. return totalHeight / arrText.length;
  9. }
  10. });
  11. var align = context.textAlign;
  12. var baseline = context.textBaseline;
  13. if (align == 'left') {
  14. x = x + Math.max.apply(null, arrWidth) / 2;
  15. } else if (align == 'right') {
  16. x = x - Math.max.apply(null, arrWidth) / 2;
  17. }
  18. if (baseline == 'bottom' || baseline == 'alphabetic' || baseline == 'ideographic') {
  19. y = y - arrWidth[0] / 2;
  20. } else if (baseline == 'top' || baseline == 'hanging') {
  21. y = y + arrWidth[0] / 2;
  22. }
  23. context.textAlign = 'center';
  24. context.textBaseline = 'middle';
  25. // 开始逐字绘制
  26. arrText.forEach(function (letter, index) {
  27. // 确定下一个字符的纵坐标位置
  28. var letterWidth = arrWidth[index];
  29. // 是否需要旋转判断
  30. var code = letter.charCodeAt(0);
  31. if (code <= 256) {
  32. context.translate(x, y);
  33. // 英文字符,旋转90°
  34. context.rotate(90 * Math.PI / 180);
  35. context.translate(-x, -y);
  36. } else if (index > 0 && text.charCodeAt(index - 1) < 256) {
  37. // y修正
  38. y = y + arrWidth[index - 1] / 2;
  39. }
  40. context.fillText(letter, x, y);
  41. // 旋转坐标系还原成初始态
  42. context.setTransform(1, 0, 0, 1, 0, 0);
  43. // 确定下一个字符的纵坐标位置
  44. var letterWidth = arrWidth[index];
  45. y = y + letterWidth;
  46. });
  47. // 水平垂直对齐方式还原
  48. context.textAlign = align;
  49. context.textBaseline = baseline;
  50. }
  51. export default drawTextVertical