Search code examples
javascripthtmldomcanvas

How do I rotate an object with the canvas api but nothing afterward?


I'm trying to make a cartoon builder app and allow the user to rotate objects but when I'm testing it, it rotates everything behind it.I fixed the roation to 270 degrees for the question, I know how to do this in p5.js and processing.js but I wanna write this in canvas api.Does anyone know if there is something that works similar to p5's pop() and push() functions?

<doctype html>
<html>
<head>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<input type="number" placeholder="width" id="width">
<input type="number" placeholder="height" id="height">
</body>
<script>
var canvas=document.getElementById("canvas")
var ctx=canvas.getContext("2d")
ctx.rotate(270);
ctx.fillRect(200,200,200,50);
//line should be flat
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(150,100);
ctx.closePath();
ctx.stroke();
</script>
<style>
canvas{
background-color:blue;
}
</style>
</html>


Solution

  • I think you want context.save();and context.restore();