How to rotate the existing content of HTML5 canvas?

前端 未结 2 1704
情深已故
情深已故 2021-01-13 05:27

Is there a way to rotate the existing content of HTML5 canvas by Javascript? I know it\'s possible to rotate an image that will be drawn on to canvas, but I want to rotate t

2条回答
  •  悲哀的现实
    2021-01-13 06:25

    If you first want to draw on a canvas and then rotate it for use on e.g. corners, you can to that when you "clone" the canvas or by using CSS.

    Examples

    Get the first canvas element:

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    

    draw on it:

    ctx.fillStyle = 'blue';
    ctx.fillRect(0,0, 25, 5);
    ctx.fill();
    ctx.fillStyle = 'red';
    ctx.fillRect(25, 0, 25, 5);
    ctx.fill();
    

    clone it to another canvas (that is rotated by CSS):

    var ctx2 = document.getElementById("canvas2").getContext("2d");
    ctx2.drawImage(canvas, 0,0);
    

    or rotate the canvas while you "clone" it:

    var ctx3 = document.getElementById("canvas3").getContext("2d");
    ctx3.rotate(Math.PI/2);
    ctx3.translate(0,-50);
    ctx3.drawImage(canvas, 0,0);
    

    here is the CSS for rotating it:

    #canvas2 {
        -webkit-transform:rotate(90deg);
        -moz-transform:rotate(90deg);
        -o-transform:rotate(90deg);
        -ms-transform:rotate(90deg);
    }
    

    enter image description here

    Here is the full example:

    
    
    
    
    
    
    
    
    
    
    
    
    

提交回复
热议问题