How to rotate the existing content of HTML5 canvas?

前端 未结 2 1721
情深已故
情深已故 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:28

    It's pretty easy to do with a temp canvas.

    Live Demo

    Live Demo Animated (just for the heck of it)

    The above example draws 2 boxes, then rotates and scales from 0,0 to 200,200

    var canvas = document.getElementById("canvas"),
        ctx = canvas.getContext("2d");
    
    canvas.width = canvas.height = 400;
    
    // fill the canvas black, and draw 2 boxes
    ctx.fillStyle = "#000";
    ctx.fillRect(0,0,400,400);
    ctx.fillStyle = "rgb(255,0,0)";
    
    ctx.fillRect(10,10,190,190);
    ctx.fillStyle = "rgb(255,255,0)";
    ctx.fillRect(250,250,90,90);
    
    // Create a temp canvas to store our data (because we need to clear the other box after rotation.
    var tempCanvas = document.createElement("canvas"),
        tempCtx = tempCanvas.getContext("2d");
    
    tempCanvas.width = canvas.width;
    tempCanvas.height = canvas.height;
    // put our data onto the temp canvas
    tempCtx.drawImage(canvas,0,0,canvas.width,canvas.height);
    
    // Append for debugging purposes, just to show what the canvas did look like before the transforms.
    document.body.appendChild(tempCanvas);
    
    // Now clear the portion to rotate.
    ctx.fillStyle = "#000";
    ctx.fillRect(0,0,200,200);
    ctx.save();
    // Translate (190/2 is half of the box we drew)
    ctx.translate(190/2, 0);
    // Scale
    ctx.scale(0.5,0.5);  
    // Rotate it
    ctx.rotate(45*Math.PI/180);
    // Finally draw the image data from the temp canvas.
    ctx.drawImage(tempCanvas,0,0,200,200,10,10,190,190);
    ctx.restore();
    

提交回复
热议问题