当前位置:首页 > JavaScript

js实现画布

2026-03-14 18:39:42JavaScript

使用Canvas API创建画布

在HTML中通过<canvas>标签创建画布元素,并设置宽度和高度属性:

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

获取画布上下文

通过JavaScript获取CanvasRenderingContext2D对象,这是绘图的核心接口:

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

绘制基本图形

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

ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 75); // 填充矩形

ctx.strokeStyle = 'blue';
ctx.lineWidth = 3;
ctx.strokeRect(200, 50, 100, 75); // 描边矩形

绘制路径(直线/三角形):

ctx.beginPath();
ctx.moveTo(50, 150);
ctx.lineTo(150, 150);
ctx.lineTo(100, 220);
ctx.closePath(); // 自动闭合路径
ctx.fillStyle = 'green';
ctx.fill();

绘制圆形与弧线

使用arc()方法绘制圆形:

ctx.beginPath();
ctx.arc(300, 150, 40, 0, Math.PI * 2);
ctx.fillStyle = 'purple';
ctx.fill();

绘制半圆:

ctx.beginPath();
ctx.arc(400, 150, 40, 0, Math.PI);
ctx.strokeStyle = 'orange';
ctx.stroke();

添加文本

设置字体样式并绘制文字:

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

ctx.strokeText('Stroke Text', 250, 280);

图像绘制

加载并绘制图像:

const img = new Image();
img.src = 'image.png';
img.onload = function() {
    ctx.drawImage(img, 350, 200, 100, 80);
};

动画实现

使用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) x = 0;
    requestAnimationFrame(animate);
}
animate();

事件交互示例

实现鼠标跟随效果:

canvas.addEventListener('mousemove', (e) => {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'rgba(0,0,255,0.5)';
    ctx.beginPath();
    ctx.arc(x, y, 30, 0, Math.PI*2);
    ctx.fill();
});

高级特性

使用save()restore()管理绘图状态:

ctx.save(); // 保存当前状态
ctx.fillStyle = 'yellow';
ctx.fillRect(50, 50, 100, 100);
ctx.restore(); // 恢复之前保存的状态

实现渐变效果:

js实现画布

const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'white');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 200);

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

相关文章

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js图片上传实现

js图片上传实现

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API实现基础图片上传功能。HTML部分需要设置accept="image/…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let curr…