我已经设法为我的画布创建了一个旋转动画,但现在我想添加一个设备运动的事件处理程序,以使我的画布在移动手机时移动。例如:现在我将画布平移到屏幕的中间点并开始旋转。当我将手机向左移动时,我希望我的中间点向左移动,反之亦然,因为我将手机向右移动。
我尝试将事件处理程序添加到我的移动函数并使用 event.accelerationIncludeGravity.x 设置画布翻译的起点,但它不起作用。我认为有问题的部分是cxt.translate(c.width / 2 - x, c.height / 2 - y);
有人可以告诉我如何做到这一点吗?这是我的代码:
const c = document.getElementById("canvas");
c.width = window.innerWidth;
c.height = window.innerHeight;
const cxt = c.getContext('2d');
function draw() {
var x1 = 0;
var y1 = 80;
var x2 = 80;
var y2 = 0;
var w = 240;
var h = 80;
for (var i = 0; i < 4; i++) {
cxt.fillStyle = "orange";
cxt.fillRect(x1, y1, w, h);
cxt.fillRect(x2, y2, h, w);
x1 -= 80;
y1 += 160;
x2 -= 80;
y2 += 160;
cxt.fillStyle = "darkred";
cxt.fillRect(x1, y1, w, h);
cxt.fillRect(x2, y2, h, w);
x1 += 240;
y1 -= 80;
x2 += 240;
y2 -= 80;
cxt.fillStyle = "black";
cxt.fillRect(x1, y1, w, h);
cxt.fillRect(x2, y2, h, w);
x1 -= 80;
y1 += 160;
x2 -= 80;
y2 += 160;
cxt.fillStyle = "blue";
cxt.fillRect(x1, y1, w, h);
cxt.fillRect(x2, y2, h, w);
x1 += 240;
y1 -= 80;
x2 += 240;
y2 -= 80;
cxt.fillStyle = "green";
cxt.fillRect(x1, y1, w, h);
cxt.fillRect(x2, y2, h, w);
x1 -= 80;
y1 += 160;
x2 -= 80;
y2 += 160;
cxt.fillStyle = "yellow";
cxt.fillRect(x1, y1, w, h);
cxt.fillRect(x2, y2, h, w);
x1 += 240;
y1 -= 80;
x2 += 240;
y2 -= 80;
}
}
function fill() {
draw();
cxt.save();
cxt.translate(0, 400);
draw();
cxt.restore();
cxt.save();
cxt.translate(160, -320);
draw();
cxt.restore();
cxt.save();
cxt.translate(960, -320);
draw();
cxt.restore();
cxt.save();
cxt.translate(-1920, -960);
draw();
cxt.restore();
cxt.save();
cxt.translate(-480, 160);
draw();
cxt.save();
cxt.translate(-480, -1440);
draw();
cxt.save();
cxt.translate(-640, 80);
draw();
cxt.save();
cxt.translate(-640, 480);
draw();
cxt.save();
}
var degree = 0;
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function move(event) {
var x = event.accelerationIncludingGravity.x;
var y = event.accelerationIncludingGravity.y;
cxt.setTransform(1, 0, 0, 1, 0, 0);
cxt.clearRect(0, 0, c.width, c.height);
cxt.translate(c.width / 2 - x, c.height / 2 - y);
cxt.rotate(degree);
fill();
degree += 0.01;
requestAnimationFrame(move);
}
move(event);
window.addEventListener("devicemotion", move, true);
使用 deviceMotionEvent.rotationRate 而不是 accleeration。
https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent/rotationRate
window.addEventListener("devicemotion", updateCanvas, true);
function updateCanvas(event) {
var rotation = event.rotationRate.gamma;
requestAnimationFrame(rotateAndTranslate);
}
function rotateAndTranslate(rotation) {
cxt.rotate(rotation);
cxt.setTransform(1, 0, 0, 1, 0, 0);
cxt.clearRect(0, 0, c.width, c.height);
cxt.translate(c.width / 2 - x, c.height / 2 - y);
fill();
}