js 做画布无限延伸
要实现无限延伸的画布,可以使用以下步骤:
- 创建画布
首先,需要在 HTML 中创建一个画布元素:
<canvas id="canvas"></canvas>
然后,在 JavaScript 中获取该元素,并设置其宽度和高度:
const canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
- 绘制图形
接下来,可以使用 Canvas API 来绘制图形。例如,可以绘制一个圆形:
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
- 监听窗口大小变化
为了让画布能够自适应窗口大小,需要监听窗口大小变化事件,并在事件触发时重新设置画布的宽度和高度:
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
- 实现无限延伸
现在,要实现无限延伸的画布,可以使用 translate() 函数来平移画布。具体地,可以在绘制图形之前调用 translate() 函数,将画布平移到当前视口的中心位置,然后绘制图形:
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
// 绘制图形
ctx.restore();
此时,画布会在视口中心绘制图形。接下来,可以通过监听鼠标移动事件,计算鼠标相对于视口中心的偏移量,然后调用 translate() 函数来平移画布,实现无限延伸:
let offsetX = 0;
let offsetY = 0;
window.addEventListener('mousemove', (e) => {
offsetX = e.clientX - canvas.width / 2;
offsetY = e.clientY - canvas.height / 2;
});
function draw() {
requestAnimationFrame(draw);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2 + offsetX, canvas.height / 2 + offsetY);
// 绘制图形
ctx.restore();
}
在上面的代码中,使用 requestAnimationFrame() 函数来实现动画效果。每次绘制图形之前,先清除画布上的内容。然后,调用 save() 函数保存当前的状态,调用 translate() 函数平移画布,绘制图形,最后调用 restore() 函数恢复之前保存的状态。
这样,就可以实现无限延伸的画布了。完整的代码如下:
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext('2d');
let offsetX = 0;
let offsetY = 0;
window.addEventListener('mousemove', (e) => {
offsetX = e.clientX - canvas.width / 2;
offsetY = e.clientY - canvas.height / 2;
});
function draw() {
requestAnimationFrame(draw);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2 + offsetX, canvas.height / 2 + offsetY);
ctx.beginPath();
ctx.arc(0, 0, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.restore();
}
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
draw();
</script>
``
原文地址: https://www.cveoy.top/t/topic/fHvW 著作权归作者所有。请勿转载和采集!