Javascript html画布,仅使用鼠标向下围绕中心旋转画布

Javascript html画布,仅使用鼠标向下围绕中心旋转画布,javascript,html,canvas,dom-events,Javascript,Html,Canvas,Dom Events,很抱歉,如果这是非常明显的重复。请求,首先在回答后标记。。我的头发都掉光了 为什么这里什么都没有?请帮助新建.html画布和.js <!DOCTYPE html> <html> <body> <canvas id="r" width="300" height="150" style="border:solid></canvas> <script> var ctx=document.getElementById("r").g

很抱歉,如果这是非常明显的重复。请求,首先在回答后标记。。我的头发都掉光了

为什么这里什么都没有?请帮助新建.html画布和.js

<!DOCTYPE html>
<html>
<body>
<canvas id="r" width="300" height="150" style="border:solid></canvas>

<script>
var ctx=document.getElementById("r").getContext("2d");

ctx.beginPath();
ctx.fillRect(50,20,100,50);

function roc(){//rotate on click
ctx.translate(r.width/2,r.height/2);
ctx.rotate(20*Math.PI/180);
}r.addEventListener("mousedown",roc)

</script>
</body>
</html>


您的代码中有几个小问题:

  • 您有对上下文(ctx)的引用,但也需要对画布(r)的引用

  • 现有矩形不能移动或旋转(它们只是画布上绘制的像素)

  • 要移动/旋转,应擦除画布并在其新旋转中重新绘制矩形

以下是注释代码和演示:


正文{背景色:象牙;}
画布{边框:1px纯红;}
$(函数(){
//获取画布和画布上下文的引用变量
var canvas=document.getElementById(“r”);
var ctx=canvas.getContext(“2d”);
//这决定了画布的旋转程度
var旋转=0;
//第一次调用roc绘制矩形
roc();
函数roc(){
//清除画布以准备新图形
//注意:不能移动/旋转现有图形!
clearRect(0,0,canvas.width,canvas.height);
//将上下文保存为未翻译的未旋转状态
ctx.save();
//平移到中心画布
//(这意味着原点[0,0]将位于画布的中心。)
ctx.平移(r.宽度/2,r.高度/2);
//将旋转角度再增加20度
旋转+=20*Math.PI/180;
//将画布旋转20度
ctx.旋转(旋转);
//画一个长方形
//矩形将旋转[旋转]度
//注意:[0,0]是中心画布,因此我们用x,y偏移1/2的宽度和高度填充
//因为fillRect将矩形的左上部分定位在x,y
宽度=100;
高度=50;
ctx.fillRect(-rectWidth/2,-rectHeight/2,rectWidth,rectHeight);
//将上下文还原到其未旋转状态
ctx.restore();
}
//听mousedown的声音,打电话给roc
r、 addEventListener(“mousedown”,roc)
});//end$(函数(){});

您的翻译只需单击一下就可以将原点从屏幕上移除…您需要执行类似的操作…注意每次都会重置原点的ctx.save()和ctx.restore()

function roc(){//rotate on click
    ctx.clearRect(0,0,r.width,r.height);
    ctx.save();
    ctx.translate(r.width/2,r.height/2);
    rotate+=10;
    ctx.rotate(rotate*Math.PI/180);
    ctx.fillRect(-50,-25,100,50);
    ctx.restore();
}
roc();
r.addEventListener("mousedown",roc)

function roc(){//rotate on click
    ctx.clearRect(0,0,r.width,r.height);
    ctx.save();
    ctx.translate(r.width/2,r.height/2);
    rotate+=10;
    ctx.rotate(rotate*Math.PI/180);
    ctx.fillRect(-50,-25,100,50);
    ctx.restore();
}
roc();
r.addEventListener("mousedown",roc)