【发布时间】:2017-11-14 06:06:16
【问题描述】:
我目前有一个画布,上面绘制了一个元素,我使用自定义函数和 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>
【问题讨论】:
-
你试过什么?您遇到了什么错误或问题?
-
我尝试设置简单的东西,比如循环来旋转画布,等等,但似乎 onclick 没有注册,因为我尝试时它没有做任何事情。
-
@JohnEllmore 我也尝试将其保存为图像然后旋转,但它也不起作用。
标签: javascript jquery html canvas