繁体   English   中英

如何在Javascript中旋转矩形

[英]How to rotate a rectangle in Javascript

大家好,我正在做一个作业,我需要画一张图释脸的图像。

function sadFace() {
//Drawing the sad face
context.beginPath();
    context.fillStyle = "rgb(255,255,0)" //Drawing the face in yellow colour
    context.lineWidth = 3;
    context.arc(300,300,200,0,Math.PI*4,true);
    context.fill();
context.stroke();
//Left Eyebrow
context.beginPath();            
    context.fillStyle = "rgb(0,0,0)";
    context.rect(170,180,90,15);
    context.fill();
context.stroke();

这是我当前的代码。 如何首先旋转图像的“眉毛”,又如何旋转眉毛而不旋转整个图像? 谢谢!

您可以使用仿射变换,例如旋转,平移,缩放。 首先保存当前上下文

context.save()

设置旋转和平移请参见文档

恢复状态

context.restore()

 const canvas = document.getElementById("canvas") const context = canvas.getContext("2d"); context.beginPath(); context.fillStyle = "rgb(255,255,0)" //Drawing the face in yellow colour context.lineWidth = 3; context.arc(300,300,200,0,Math.PI*4,true); context.fill(); context.stroke(); //Left Eyebrow context.save(); context.translate(210, 188); context.rotate(30 * Math.PI / 180); context.beginPath(); context.fillStyle = "rgb(0,0,0)"; context.rect(-45,-8,90,15); context.fill(); context.stroke(); context.restore(); context.save(); context.translate(380, 188); context.rotate(-30 * Math.PI / 180); context.beginPath(); context.fillStyle = "rgb(0,0,0)"; context.rect(-45,-8,90,15); context.fill(); context.stroke(); context.restore(); 
 <canvas id="canvas" width="500" height="500" /> 

说明:

由于旋转是围绕协调器旋转的(O(0,0),因此我们需要先translate移到要绘制的位置:

context.translate(eyeBrowX, eyeBrowY); // eyebrow position here

然后做一个rotation

context.rotate(angleInRadian);

然后绘制矩形,使矩形的中心为O(0,0)-然后它将围绕其中心旋转。

context.beginPath();            
context.fillStyle = "rgb(0,0,0)";
context.rect(-width / 2, -height / 2, width, height);
context.fill();
context.stroke();

您无需旋转任何东西。 不用创建rect只是用线条画眉毛。 告诉这条线在这样的对角线路径中绘制

  let canvas = document.getElementById("myCanvas"); let context = canvas.getContext("2d"); context.beginPath(); context.fillStyle = "rgb(255,255,0)" //Drawing the face in yellow colour context.lineWidth = 3; context.arc(300,300,200,0,Math.PI*4,true); context.fill(); context.stroke(); //Left Eyebrow context.beginPath(); context.moveTo(170,180); context.lineTo(260,195); context.lineWidth = 10 context.fillStyle = "rgb(0,0,0)"; context.fill(); context.stroke(); 
  <canvas id="myCanvas" width="800" height="800"></canvas> 

这样,您无需保存上下文。 顺便说一下, canvas不允许您单独更改内容。 您需要清除并重新绘制。 (例如它如何用于动画)。 如果您需要更多控制权并单独修改,则需要一个渲染库,例如Pixi.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM