JS 使用OffscreenCanvasRenderingContext2D绘制气泡框

130 阅读1分钟

使用OffscreenCanvasRenderingContext2D绘制气泡框

记录如何使用# OffscreenCanvasRenderingContext2D绘制自定义的气泡框

测试项目结构如下:

image.png

运行效果如下:

image.png

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>OffscreenCanvas Bubble Demo</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <canvas id="mainCanvas" width="800" height="600" backgroundColor='#f0f0f0'></canvas>
  <button>Start</button>

  <script src="script.js"></script>
</body>

</html>

style.css

body,
html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f7f7f7;
}

canvas {
  border: 1px solid #000;
}

script.js

const canvas = document.getElementById('mainCanvas');
const ctx = canvas.getContext('2d');

// 创建OffscreenCanvas
const offscreenCanvas = new OffscreenCanvas(500, 400);

const offscreenCtx = offscreenCanvas.getContext('2d');

// 定义气泡框的样式
offscreenCtx.fillStyle = '#FFD700'; // 金色填充
offscreenCtx.strokeStyle = 'red'; // 红色边框

// 定义气泡框的大小和圆角半径
const bubbleWidth = 200;
const bubbleHeight = 100;
const cornerRadius = 10;

// 计算气泡框的位置
const bubbleX = (offscreenCanvas.width - bubbleWidth) / 2;
const bubbleY = (offscreenCanvas.height - bubbleHeight) / 2;

// 设置气泡框的角坐标位置

// 开始绘制气泡框
offscreenCtx.beginPath();

// 绘制左下角的圆角
offscreenCtx.arc(bubbleX + cornerRadius, bubbleY - cornerRadius, cornerRadius, Math.PI, Math.PI / 2, true);

// 绘制气泡框的尖角
offscreenCtx.lineTo(bubbleX + 30 + cornerRadius, bubbleY);
offscreenCtx.lineTo(bubbleX + 60 + cornerRadius, bubbleY + 70);
offscreenCtx.lineTo(bubbleX + 70 + cornerRadius, bubbleY);

// 绘制下侧的直线
offscreenCtx.lineTo(bubbleX + bubbleWidth - cornerRadius, bubbleY);

// 绘制右下角的圆角
offscreenCtx.arc(bubbleX + bubbleWidth - cornerRadius, bubbleY - cornerRadius, cornerRadius, Math.PI / 2, 0, true);

// 绘制右侧的直线
offscreenCtx.lineTo(bubbleX + bubbleWidth, bubbleY - bubbleHeight + cornerRadius);

// 绘制右上角的圆角
offscreenCtx.arc(bubbleX + bubbleWidth - cornerRadius, bubbleY - bubbleHeight + cornerRadius, cornerRadius, 0, -Math.PI / 2, true);

// 绘制顶部直线
offscreenCtx.lineTo(bubbleX + cornerRadius, bubbleY - bubbleHeight);
// 绘制左上角的圆角
offscreenCtx.arc(bubbleX + cornerRadius, bubbleY - bubbleHeight + cornerRadius, cornerRadius, -Math.PI / 2, Math.PI, true);

// 关闭路径
offscreenCtx.closePath();

// 填充气泡框
offscreenCtx.fill();
offscreenCtx.stroke();

// 将OffscreenCanvas内容绘制到主Canvas
ctx.drawImage(offscreenCanvas, 0, 0);