五、Canvas基本绘图

Canvas绘图(四)

本章将介绍Canvas渲染文本方面的操作,而对于浏览器的支持度参差不齐,可以使用modernizr.js这个库提供支持,注意Canvas的文本不能使用css样式,但是它的属性与css属性相似。

本章内容较少

  • 基本文本
  • 文本渐变动画

一、基本文本

要在Canvas上显示文本,首先需要通过 font 设置文本的属性

  • font-style[normal | italic | oblique ]
  • font-weight [normal | bold | border | lighter | 100~900 | auto | inherit | auto ]
  • font-size
  • font-face [serif | sans-serif | cursive | fantasy | monospace ]

例如

drawText() {
    this.context.font = "50px serif";
    this.context.font = "normal bold 50px serif";
    this.context.fillStyle = "#ff0000";
    this.context.fillText("Hellow World", 100, 80);
}

A. 表单与画布通信

与DOM绑定事件没有什么不同,绑定事件需要重绘整个Canvas

setup() {
    this.bindEvent();
}

bindEvent() {
    const formElement = document.getElementById("textBox");
    formElement.addEventListener(
        "keyup",
        this._textBoxChange.bind(this),
        false
    );
}

_textBoxChange(e) {
    this.message = e.target.value;
    this.drawScreen();
}

drawScreen() {
    this.context.fillStyle = "#ff0000";
    this.context.fillText(this.message, 100, 80);
}

B. MeasureText

Canvas有一个用于返回字体在当前环境的文本属性

接口 说明
measureText(str) 返回一个TextMetrics对象,该对象包含文本的属性

a . 居中地输入文本

drawScreen() {
    this.context.fillStyle = "#ff0000";
    const metrics = this.context.measureText(this.message);
    const textWidth = metrics.width;
    const xPosition = this.theCanvas.width / 2 - textWidth / 2;
    this.context.fillText(this.message, xPosition, 80);
}

b. 计算文本高度

TextMetrics对象并不包含高度属性,我们现阶段只能简单的将文本渲染在画布中央

const yPosition = this.theCanvas.height / 2;
this.context.fillText(this.message, xPosition, yPosition);

C. StrokeText

strokeText()这个方法与fillText()类似,但前者是描边的效果,方法如下

接口 说明
strokeText(text,x,y,maxWidth) 在画布上使用文本笔触进行描边

还可以使用strokeStyle()方法设置描边的颜色

this.context.strokeStyle = '#66ccff'
this.context.strokeText(this.message, xPosition, yPosition);

D. 基线与对齐

a. 垂直对齐

可以通过设置context.textBaseline来对基线进行设置,例如 :

  • top : 文本顶端
  • hanging : 比top稍低
  • middle : 绝对垂直居中于基线
  • alphabetic : 垂直书写字体的底部,例如阿拉伯文、拉丁文与西伯来文
  • bottom : 文本底部

b. 水平对齐

context.textAlign设置关于x轴的文本位置,它有以下属性

  • center : 文本绝对水平居中
  • start : 从y轴前端开始显示
  • end : 从y轴末尾开始显示
  • left : 文本最左端从y轴位置开始
  • right : 文本最右端从y轴位置开始

E. 全局阴影、渐变、图案

阴影与透明度对文字也是有效的

this.context.shadowOffsetX = this.shadowOffsetX;
this.context.shadowOffsetY = this.shadowOffsetY;
this.context.shadowColor = this.shadowColor;
this.context.shadowBlur = this.shadowBlur;

文本渐变应用前几章的学习的渐变效果,需要注意的是,在创建线性渐变时,起点需要位于文本开始处并结束于文本宽度。例如 :

const metrics = this.context.measureText(this.message)
const textWidth = metrics.width 
const gradient = this.context.createLinerGradient(100,100,textWidth,100)
gradient.addColorStop(0,'#000')
gradient.addColorStop(.5,'#fff')
this.context.fillStyle = gradient

若要使用图案填充,则需要调用Canvas环境的createPattern,再

const pattern = this.context.createPattern(patternImg,'repeat')
this.context.fillStyle = pattern

实例 : 文本处理器

1601784040135.png

代码贴在另外一篇文章

二、文字动画

Canvas的动画比HTML强得多,例如在使用渐变效果时,不仅能编辑文本,还能动态创建文本,例如做一个渐变的文字动画

import "@s/assets/style/normalize.scss";
import helloworld from "@s/assets/images/helloworld.jpg";

class CanvasApp {
  constructor() {
    this.theCanvas = document.getElementById("canvasOne");
    this.context = this.theCanvas.getContext("2d");
    this.fadeIn = true;
    this.text = "Hello World";
    this.alpha = 0;
    this.colorStops = [
      {
        color: "#ff0000",
        stopPercent: 0,
      },
      {
        color: "#ffff00",
        stopPercent: 0.125,
      },
      {
        color: "#00ff00",
        stopPercent: 0.375,
      },
      {
        color: "#0000ff",
        stopPercent: 0.625,
      },
      {
        color: "#ff00ff",
        stopPercent: 0.875,
      },
      {
        color: "#ff0000",
        stopPercent: 1,
      },
    ];
  }
  setup() {
    const helloWorldImage = new Image();
    helloWorldImage.onload = () => {
      this.context.drawImage(helloWorldImage, 0, 0, 720, 300);
    };
    helloWorldImage.src = helloworld;
    this.gameLoop(this.drawScreen);
  }
  gameLoop(callback) {
    window.requestAnimationFrame(this.gameLoop.bind(this, callback));
    callback.call(this);
  }
  drawScreen() {
    const gradient = this.context.createLinearGradient(
      this.theCanvas.width / 2,
      0,
      this.theCanvas.width / 2,
      this.theCanvas.height
    );

    this.colorStops.forEach((stop) => {
      const tempColor = stop.color;
      let tempStopPercent = stop.stopPercent;
      gradient.addColorStop(tempStopPercent, tempColor);
      tempStopPercent += 0.015;
      if (tempStopPercent > 1) {
        tempStopPercent = 0;
      }
      stop.stopPercent = tempStopPercent;
    });
    this.context.globalAlpha = 1;
    this.context.fillStyle = gradient;
    this.context.fillRect(0, 0, 720, 300);
    this.context.font = "72px Sans-Serif";
    this.context.textBaseline = "top";
    this.context.fillStyle = "#ffffff";
    this.context.fillText(this.text, 150, 120);
  }
}

new CanvasApp().setup();
1601809888796.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。