gpt4 book ai didi

javascript - 如何旋转HTML5 canvas已有的内容?

转载 作者:太空狗 更新时间:2023-10-29 16:52:51 25 4
gpt4 key购买 nike

有没有办法通过 Javascript 旋转 HTML5 canvas 的现有内容?我知道可以旋转将绘制到 Canvas 上的图像,但我想旋转已绘制到 Canvas 上的内容,例如,400x400 Canvas 的 200x200 Angular ,或现有 Canvas 的任何特定区域.

缩放现有 Canvas 内容的相同问题...

我知道 getImageData/putImageData 提供了转换像素阵列的潜力,但它太慢且效率低下。

最佳答案

使用临时 Canvas 非常容易。

Live Demo

Live Demo Animated (只是为了它)

上面的例子画了2个盒子,然后从0,0旋转缩放到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();

关于javascript - 如何旋转HTML5 canvas已有的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8517879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com