当前位置:首页 > JavaScript

js 实现画布

2026-02-01 10:28:16JavaScript

使用 Canvas API 绘制基础图形

在 HTML 中创建 <canvas> 元素并设置宽高:

<canvas id="myCanvas" width="400" height="300"></canvas>

通过 JavaScript 获取画布上下文:

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

绘制矩形(填充与描边):

ctx.fillStyle = 'red'; // 设置填充颜色
ctx.fillRect(50, 50, 100, 80); // (x, y, width, height)

ctx.strokeStyle = 'blue'; // 设置描边颜色
ctx.lineWidth = 3; // 线宽
ctx.strokeRect(200, 50, 100, 80);

绘制路径与自定义形状

使用路径绘制三角形:

ctx.beginPath();
ctx.moveTo(100, 150); // 起点
ctx.lineTo(150, 250);
ctx.lineTo(50, 250);
ctx.closePath(); // 闭合路径
ctx.fillStyle = 'green';
ctx.fill();

绘制圆形/圆弧:

ctx.beginPath();
ctx.arc(300, 200, 50, 0, Math.PI * 2); // (x, y, radius, startAngle, endAngle)
ctx.strokeStyle = 'purple';
ctx.stroke();

添加文本与图像

绘制文本:

ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 50, 30);

ctx.strokeText('Outline Text', 200, 30);

加载并绘制图像:

const img = new Image();
img.src = 'image.png';
img.onload = () => {
  ctx.drawImage(img, 250, 150, 100, 100); // (image, x, y, width, height)
};

实现动画效果

使用 requestAnimationFrame 创建动画:

let x = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
  ctx.fillRect(x, 100, 50, 50);
  x += 2;
  if (x < canvas.width) {
    requestAnimationFrame(animate);
  }
}
animate();

处理用户交互

监听鼠标事件实现绘图板:

let isDrawing = false;
canvas.addEventListener('mousedown', () => isDrawing = true);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mousemove', (e) => {
  if (!isDrawing) return;
  ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
});

保存画布内容

将画布导出为图像:

js 实现画布

document.getElementById('saveBtn').addEventListener('click', () => {
  const dataURL = canvas.toDataURL('image/png');
  const link = document.createElement('a');
  link.download = 'drawing.png';
  link.href = dataURL;
  link.click();
});

标签: 画布js
分享给朋友:

相关文章

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获…

js实现换肤

js实现换肤

使用CSS变量实现换肤 通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。 :root { --primary-color: #349…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现图

js实现图

JavaScript 实现图的常用方法 在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix…