javascript - 图像不在画布内旋转
问题描述
我通过stackoverflow搜索并找到了一些有助于旋转图像的代码,但它不起作用。我没有看到任何错误,并且它正在获取弧度和度数,所以事情应该可以正常工作,但是画布中的图像不会旋转。
当用户单击画布然后移动鼠标时,代码应该开始旋转图像。当他们在页面或画布上释放鼠标时,它应该停止图像的旋转。
<script type="text/javascript">
var mouseDown = false;
var intID;
var mouse_x = 0;
var mouse_y = 0;
var canvas;
var img;
function init()
{
canvas = document.getElementById("wheelCanvas");
img = new Image();
img.src = 'images/wheel.png';
img.onload = function() {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, img.width, img.height);
}
canvas.onmousedown = function(event)
{
mouseDown = true;
intID = setInterval(rotateWheel, 100);
}
canvas.onmouseup = function(event)
{
mouseDown = false;
clearInterval(intID);
}
canvas.onmousemove = function(event)
{
if(mouseDown)
{
mouse_x = event.pageX;
mouse_y = event.pageY;
}
}
document.onmouseup = function(event)
{
mouseDown = false;
clearInterval(intID);
}
}
function rotateWheel()
{
var ctx = canvas.getContext("2d");
var center_x = canvas.width / 2;
var center_y = canvas.height / 2;
var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
var degree = Math.round((radians * (180 / Math.PI) * -1) + 180);
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(425,425);
ctx.rotate(degree*(Math.Pi/180));
ctx.drawImage(img, -img.width/2, -img.height/2);
ctx.restore();
console.log(degree);
if(!mouseDown) { clearInterval(intID); }
}
</script>
解决方案
您在该行输入了“Math.Pi”而不是“Math.PI”
ctx.rotate(degree*(Math.Pi/180));
推荐阅读
- git - 如何在 Git 中恢复其他人的提交?
- mocking - 使用 OpenAPI 3.0 是否可以将布尔查询参数链接到特定示例
- python - 如何检查 DataFrame 列中是否存在元组值
- python - 使用 Spark 数据框列作为键访问字典值
- database - 微服务和数据库更改
- awk - 从文本文件中获取匹配对
- python - 是否可以使用 Dialogflow CX 代理自动响应 Linkedin 上的私人消息?
- ios - 反应本机和自定义键盘目标 Xcode
- sqlite - AUTO INCREMENT 同一列中的字符和整数
- r - 对 R 中的所有列按年应用运行平均值