我目前有一个画布,上面有一个元素,我使用自定义函数和onload函数进行绘制。我想知道如何通过跟随鼠标360度旋转这个画布,就像转动车轮一样。代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Help</title>
</head>
<body>
<canvas id="MyCanvas" width="500" height="500"></canvas>
<script>
var ctx = document.getElementById("MyCanvas").getContext("2d");
ctx.translate(250,250);
function draw(){
ctx.arc(0,0,100,0,Math.PI*2,false); // x, y, radius, start angle, end angle, false/true
ctx.stroke();
ctx.beginPath();
ctx.moveTo(-100,0);
ctx.lineTo(100,0);
ctx.moveTo(100,0);
ctx.lineTo(60,-80);
ctx.moveTo(60,-80);
ctx.lineTo(-100,0);
ctx.stroke();
}
window.onload=draw;
</script>
</body>
</html>
有人知道如何做到这一点吗?我尝试了多个不同的函数,但它们似乎都无法实现任何功能。非常感谢您的帮助。
编辑过,但有轻微问题。
<!DOCTYPE html>
<html>
<head>
<title>Help</title>
</head>
<style>
canvas{
border: 2px solid black;
}
</style>
<body>
<canvas id="Canvas" height="300"></canvas>
<script>
const ctx = canvas.getContext("2d");
const mouse = { x: 0, y: 0 };
function mouseEvents(e) {
const bounds = canvas.getBoundingClientRect();
mouse.x = e.pageX - bounds.left - scrollX;
mouse.y = e.pageY - bounds.top - scrollY;
}
document.addEventListener("mousemove", mouseEvents);
function drawRotated(x, y, angle) {
ctx.setTransform(1, 0, 0, 1, x, y);
ctx.rotate(angle);
ctx.beginPath();
ctx.arc(0, 0, 100, 0, Math.PI * 2);
ctx.moveTo(-100, 0);
ctx.lineTo(100, 0);
ctx.lineTo(60, -80);
ctx.closePath();
ctx.stroke();
}
function update(timer) {
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.clearRect(0, 0, 300, 300);
var angle = Math.atan2(mouse.y - 150, mouse.x - 150);
drawRotated(150, 150, angle);
requestAnimationFrame(update);
}
requestAnimationFrame(update);
</script>
</body>
</html>