兔年了,用 canvas 画一个兔子印章🐰

437 阅读1分钟

图片.png

我正在参加「兔了个兔」创意投稿大赛,详情请看:「兔了个兔」创意投稿大赛

嘿嘿,提前祝大家新年快乐啊

R-C.gif

初始化 canvas

let canvas = document.getElementById('canvas')
let context = canvas.getContext('2d')

canvas.width = canvasSize
canvas.height = canvasSize

定义常量

const lineWidth = 4
const company = '快速将任意组件集成到低代码平台'
const canvasSize = 400
const name = '兔年印章'

绘制外形圆圈

let width = canvas.width / 2
let height = canvas.height / 2

// 设置当前的线条宽度
context.lineWidth = lineWidth
// 设置用于笔触的颜色、渐变或模式
context.strokeStyle = 'red'
context.beginPath();
// arc() 方法创建弧/曲线(用于创建圆或部分圆)
context.arc(width, height, width - lineWidth, 0, Math.PI * 2);
context.stroke();

印章名称

// 描述颜色和样式
context.fillStyle = 'red';
context.font = `16px Helvetica`;
// 设置文本的垂直对齐方式
context.textBaseline = 'middle';
// 设置文本的水平对对齐方式
context.textAlign = 'center';
context.lineWidth = 1;
context.fillText(name, width, height + 140);

环形文字

// translate() 方法重新映射画布上的 (0,0) 位置
context.translate(width, height);
let count = company.length;
let angle = 4 * Math.PI / (3 * (count - 1));
let chars = company.split("");
let c;
for (let i = 0; i < count; i++) {
  // 需要绘制的字符
  c = chars[i];
  if (i == 0)
   // rotate() 方法旋转当前的绘图
    context.rotate(5 * Math.PI / 6);
  else
    context.rotate(angle);
  context.save();
  // 平移到此位置,此时字和x轴垂直
  context.translate(canvas.width / 2.22, 0);
  // 旋转90度,让字平行于x轴
  context.rotate(Math.PI / 2);
  // 此点为字的中心点
  context.fillText(c, 0, 20);
  context.restore();
}

中心图片

// 主要是用于
if (!imgRef.current) {
  const img = new Image()
  imgRef.current = img
  img.src = 'https://s1.ax1x.com/2023/01/07/pSEhQLd.png'
  img.onload = function () {
    context.rotate(330 * Math.PI / 180)
    // drawImage() 方法在画布上绘制图像、画布或视频
    // drawImage() 方法也能够绘制图像的某些部分,以及/或者增加或减少图像的尺寸
    context.drawImage(this, - width / 2, - height / 2)
  }
}

这样子,我们的兔年印章就完美实现了。

R-C.gif