跳转到内容

Canvas 设计 (canvas-design)

canvas-design 是使用 原生 JavaScript 和 Canvas API 创建交互式 Canvas 体验的技能。

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 矩形
ctx.fillRect(x, y, width, height);
ctx.strokeRect(x, y, width, height);
// 圆形
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.fill();
ctx.stroke();
// 路径
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.closePath();
// 颜色
ctx.fillStyle = 'red';
ctx.strokeStyle = 'blue';
// 线宽
ctx.lineWidth = 2;
// 字体
ctx.font = '24px Arial';
ctx.fillText('Hello', x, y);
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制
draw();
// 更新
update();
requestAnimationFrame(animate);
}
animate();
// 完全清除
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 拖尾效果
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// 处理点击
});
canvas.addEventListener('mousemove', (e) => {
// 处理移动
});
canvas.addEventListener('mouseup', () => {
// 处理释放
});
document.addEventListener('keydown', (e) => {
if (e.key === 'ArrowRight') {
// 向右移动
}
});
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mouseup', () => isDrawing = false);
let player = { x: 100, y: 100, size: 20 };
let keys = {};
document.addEventListener('keydown', e => keys[e.key] = true);
document.addEventListener('keyup', e => keys[e.key] = false);
function update() {
if (keys['ArrowUp']) player.y -= 5;
if (keys['ArrowDown']) player.y += 5;
if (keys['ArrowLeft']) player.x -= 5;
if (keys['ArrowRight']) player.x += 5;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'blue';
ctx.fillRect(player.x, player.y, player.size, player.size);
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();

绘制

fillRect, arc, beginPath

样式

fillStyle, strokeStyle, lineWidth

动画

requestAnimationFrame, clearRect

交互

mousedown, mousemove, keydown


查看源文件: GitHub原始文件