Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/476.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何创建用于使用JavaScript画布旋转的通用函数?_Javascript_Canvas_Html5 Canvas_2d - Fatal编程技术网

如何创建用于使用JavaScript画布旋转的通用函数?

如何创建用于使用JavaScript画布旋转的通用函数?,javascript,canvas,html5-canvas,2d,Javascript,Canvas,Html5 Canvas,2d,我正在构建一些JavaScript组件来处理一般的画布绘制,我很难实现旋转。我有一个类似的函数,它被简化了很多 function drawThing (ctx, posX, posY, sizeX, sizeY, rotation, drawFn) { // `ctx` is the 2d canvas context ctx.save(); ctx.beginPath(); // Not sure if this is needed ctx.translate(

我正在构建一些JavaScript组件来处理一般的画布绘制,我很难实现旋转。我有一个类似的函数,它被简化了很多

function drawThing (ctx, posX, posY, sizeX, sizeY, rotation, drawFn) {
    // `ctx` is the 2d canvas context
    ctx.save();
    ctx.beginPath(); // Not sure if this is needed
    ctx.translate(posX, posY); // What do I use here?
    ctx.rotate(rotation); // rotation is in radians
    drawFn(ctx, posX, posY, sizeX, sizeY);
    ctx.restore();
}
function exampleDrawFn (ctx, posX, posY, sizeX, sizeY) {
    ctx.fillStyle = "#333";
    ctx.fillRect((posX - sizeX/2), (posY - sizeY/2), sizeX, sizeY);
}
我不知道翻译参数使用什么;或者可能在某个地方有不同的错误


虽然有点复杂,但下面是我正在处理的代码:

我能够解决这个问题,但在旋转后反转了平移

function drawThing (ctx, posX, posY, sizeX, sizeY, rotation, drawFn) {
    ctx.save();
    ctx.translate(posX, posY);
    ctx.rotate(rotation);
    ctx.translate(-posX, -posY);
    drawFn(ctx, posX, posY, sizeX, sizeY);
    ctx.restore();
}

我很好奇这种方法是否还有改进的余地,但我相信这应该是可行的。

目前最快的画图方法

function drawImage (image, x, y, sizeX, sizeY, rot) {
    var xdx = Math.cos(rot);  // direction of x axis
    var xdy = Math.sin(rot);
    ctx.setTransform(
        xdx, xdy,  // set the direction of the x axis
        -xdy, xdx, // set the direction of the y axis (at 90 deg clockwise from x axis
        x, y       // set the origin the point around which to rotate
    );
    ctx.drawImage(image,- sizeX / 2, -sizeY / 2, sizeX, sizeY);
}
假设在渲染图像时希望图像围绕其中心旋转,该中心位于点x,y处,则可以使用ctx重置为默认变换。setTransform1,0,0,1,0,0

这比

function drawImage(image, x, y, sizeX, sizeY, rot){
    ctx.setTransform(1, 0, 0, 1, x, y);
    ctx.rotate(rot);
    ctx.drawImage(image, -sizeX / 2, -sizeY / 2, sizeX, sizeY);
}

。。。在FF和Chrome上,但明天可能不是这样。

只是ctx中的一个输入错误。drawImage方法:-sizeX/2和setTransform。。。不}不幸的是,当我试图实现它时,它没有工作/没有做与我的函数完全相同的事情。@luke哦,真遗憾。抱歉,没有更多详细信息,我无法确定您是否正在将原点移向或移离渲染位置,或者,如果您依赖于以前的任何转换状态来呈现您的东西。@Blindman67-这里有一个JSFIDLE比较了这两种方法:@Luke您可以自由使用ctx.save和restore,但是如果您经常使用它们,那么这两种操作的成本会很高。ctx.setTransform将替换当前转换状态,因此不需要使用保存和还原。它允许每帧渲染1000多个旋转缩放的精灵,这是使用“保存和还原”渲染时无法做到的。要获得默认回拨ctx.setTransform1,0,0,1,0,0,比恢复快得多。