HTML Canvas Context rotate and transform

Description

HTML Canvas Context rotate and transform

View in separate window

<!DOCTYPE html>
<html>
<body>

<canvas id="canvas" width="640" height="280" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
  let theCanvas = document.getElementById('canvas');
    let context = theCanvas.getContext('2d');
    //now draw a red square
    context.setTransform(1,0,0,1,0,0)/*w  w w . j  a  v  a 2s  . co m*/
    let angleInRadians =45 * Math.PI / 180;
    let x=50;
    let y=100;
    let width=40;
    let height=40;
    context.translate(x+.5*width, y+.5*height)
    context.rotate(angleInRadians);
    context.fillStyle = "red";
    context.fillRect(-.5*width,-.5*height , width, height);
    
    context.setTransform(1,0,0,1,0,0)
    angleInRadians =75 * Math.PI / 180;
    x=100;
    y=100;
    width=40;
    height=40;
    context.translate(x+.5*width, y+.5*height)
    context.rotate(angleInRadians);
    context.fillStyle = "red";
    context.fillRect(-.5*width,-.5*height , width, height);
    
    context.setTransform(1,0,0,1,0,0)
    angleInRadians =90 * Math.PI / 180;
    x=150;
    y=100;
    width=40;
    height=40;
    context.translate(x+.5*width, y+.5*height)
    context.rotate(angleInRadians);
    context.fillStyle = "red";
    context.fillRect(-.5*width,-.5*height , width, height);
    
    context.setTransform(1,0,0,1,0,0)
    angleInRadians =120 * Math.PI / 180;
    x=200;
    y=100;
    width=40;
    height=40;
    context.translate(x+.5*width, y+.5*height)
    context.rotate(angleInRadians);
    context.fillStyle = "red";
    context.fillRect(-.5*width,-.5*height , width, height);
    

</script>

</body>
</html>



PreviousNext

Related