[英]How to rotate a particular element without affecting other elements in canvas?
当用户按下向右/向左键时,我正在尝试移动水箱。 当我使用rotate()
它会影响画布的所有元素。 有没有一种方法只能在用户按下向右或向左键时移动水箱的第三个矩形?
目的是在按下按键时将角度更改一定量。 我进行了搜索,但找不到足以让我理解如何实现它的基本知识。
var canvas=document.getElementById('canvas'); var ctx=canvas.getContext('2d'); var rightPressed=false; var leftPressed=false; var score1=0; var score2=0; var turn=0; document.addEventListener("keydown",keyDownHandler,false); document.addEventListener("keyup",keyUpHandler,false); function keyDownHandler(e) { if(e.keyCode==37) leftPressed=true; else if(e.keyCode==39) rightPressed=true; } function keyUpHandler(e) { if(e.keyCode==37) leftPressed=false; else if(e.keyCode==39) rightPressed=false; } function drawMountain() { ctx.beginPath(); ctx.moveTo(250, 400); ctx.bezierCurveTo(250, 100, 500, 100, 500, 400); ctx.fillStyle="green"; ctx.fill(); ctx.closePath(); } function drawTanks() { ctx.beginPath(); ctx.rect(20,360,50,40); ctx.rect(620,360,50,40); ctx.rect(30,340,30,20); ctx.rect(630,340,30,20); ctx.rect(40,300,10,40); ctx.rect(640,300,10,40); ctx.fillStyle="blue"; ctx.fill(); ctx.closePath(); } function rotateTank() { ctx.beginPath(); ctx.rect(20,20,130,40); ctx.rect(560,20,130,40); ctx.fillStyle="green"; ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.fillStyle="white"; ctx.font="20px Verdana"; ctx.fillText('Player 1: '+ score1,28,45); ctx.closePath(); ctx.beginPath(); ctx.fillStyle="white"; ctx.font="20px Verdana"; ctx.fillText('Player 2: '+ score2,570,45); ctx.closePath(); } function drawGame() { ctx.clearRect(0,0,canvas.width,canvas.height); drawMountain(); drawTanks(); rotateTank(); } setInterval(drawGame,10);
#canvas { background-color: black; }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="game.css"> </head> <body> <center><canvas id="canvas" width="700" height="400"></canvas></center> <script src="game.js"> </script> </body> </html>
假设我们有两个矩形。
ctx.fillStyle = "#F00";
ctx.fillRect(10, 10, 20, 10);
ctx.fillStyle = "#00F";
ctx.fillRect(50, 50, 20, 10);
您只想旋转第一个。
有两种方法可以做到这一点:
将红色矩形移到蓝色矩形后再旋转
ctx.fillStyle = "#00F";
ctx.fillRect(50, 50, 20, 10);
ctx.rotate(20*Math.PI/180);
ctx.fillStyle = "#F00";
ctx.fillRect(10, 10, 20, 10);
只需将ctx.rotate设置为红色矩形后的负数(在我们的示例中为-20)
ctx.rotate(20*Math.PI/180);
ctx.fillStyle = "#F00";
ctx.fillRect(10, 10, 20, 10);
ctx.rotate(-20*Math.PI/180); //This "resets" the rotation.
ctx.fillStyle = "#00F";
ctx.fillRect(50, 50, 20, 10);
这是一个代码片段:
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext('2d'); function draw() { ctx.rotate(20*Math.PI/180); ctx.fillStyle = "#F00"; ctx.fillRect(10, 10, 20, 10); ctx.rotate(-20*Math.PI/180); ctx.fillStyle = "#00F"; ctx.fillRect(50, 50, 20, 10); } draw();
<canvas id="canvas" width=100 height=100 style="border: 1px solid #000"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.