JSFiddle - React, Tailwind, and code Playground

by brigand

HTML

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>test canvas translate and rotate</title>
	</head>
	<body>
		<main style="width: 900px; margin: auto; ">

			<canvas width="500px" height="800px" style="display: block; width:500px; margin:25px auto;"></canvas>
		</main>
		<script src="testCNVtranslateRotate02.js"></script>
	</body>
</html>

JavaScript

var canvas = document.querySelector("body>main>canvas"),
  ctx = canvas.getContext("2d"),
  w = 500,
  h = 800;

ctx.fillStyle = "#ddf";
ctx.strokeStyle = "#0f0";
ctx.fillRect(0, 0, w, h);


function drawTriangle(direction, color, size) {
  // direction 0=right, no rotation
  // 1=left, 180deg rotation
  // 2=up -90 or +270 deg rotation
  // 4=down +90 or -270 deg rotation

  ctx.save();
  // if(direction==0){
  if (!direction) {
    //no rotation
  } else if (direction == 1) {
    // 1=left, 180deg rotation
    ctx.rotate(3.145);
  }
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(0, -size); //up five
  ctx.lineTo(size, 0); //to the right 5
  ctx.lineTo(0, size);
  ctx.closePath();
  ctx.fill();

  ctx.restore();
}

ctx.save();
ctx.translate(5, 30);
drawTriangle(0, "#f44", 25);
ctx.restore();

ctx.save();
ctx.translate(50, 100);
drawTriangle(0, "#f44", 25); //right, red
drawTriangle(1, "#44f", 25); //left, blue
// ALL BECOME BLUE????????????
ctx.restore();