在画布中以不旋转画布的角度绘制图像

问题描述

| 我正在使用JavaScript中的画布在HTML 5中绘制图像。我需要以旋转角度绘制它。我知道可以通过使用画布的上下文应用rotate(angle)函数来完成此操作。但是我需要做到这一点,而不需要旋转画布本身。 如果可能的话,请提出可能的解决方案。     

解决方法

        实际上,您可以将要旋转的任何内容绘制到屏幕外的画布中,然后将其绘制到主画布中。我从Google IO Talk借来了以下代码:
rotateAndCache = function(image,angle) {
  var offscreenCanvas = document.createElement(\'canvas\');
  var offscreenCtx = offscreenCanvas.getContext(\'2d\');

  var size = Math.max(image.width,image.height);
  offscreenCanvas.width = size;
  offscreenCanvas.height = size;

  offscreenCtx.translate(size/2,size/2);
  offscreenCtx.rotate(angle + Math.PI/2);
  offscreenCtx.drawImage(image,-(image.width/2),-(image.height/2));

  return offscreenCanvas;
}
然后将其缓存:
rotobj = rotateAndCache(myimg,myangle)
并在您的drawcode中:
mycontext.drawImage(rotobj,x_coord,y_coord)
仅当您的对象仅旋转一次角度并且随后仅进行变换时,此功能才有用。     ,        在画布上应用变换时,不会旋转画布。您只是告诉您所有要绘制的内容都会以特定方式进行转换。如果要避免转换影响其他命令,请使用
save()
restore()
方法。它们允许保存和恢复画布的设置。
ctx.save();
ctx.rotate(30);
ctx.drawImage();
ctx.restore();
    ,        我对@PeterT表示赞赏-摘录非常好,效果很好-谢谢!我确实需要进行3个小更改才能使它对我有用: 1.宽度和高度的最大值还不够:如果您想旋转正方形,则需要一个直径为正方形对角线的圆(circle6ѭ)。 2.需要将画布翻译回(或使用保存/还原)。 3.必须针对画布大小调整对象的x和y坐标。 所以我最终得到了:
    rotateAndCache = function(image,angle) {
        var offscreenCanvas = document.createElement(\'canvas\');
        var offscreenCtx = offscreenCanvas.getContext(\'2d\');

        var size = Math.max(image.width,image.height);
        var diam = 2*((size/2)*Math.sqrt(2));                 // needs to be saved
        offscreenCanvas.width = diam;
        offscreenCanvas.height = diam;

        offscreenCtx.translate(diam/2,diam/2);
        offscreenCtx.rotate(angle);
        offscreenCtx.drawImage(image,-(image.height/2));
        offscreenCtx.translate(-diam/2,-diam/2);

        return offscreenCanvas;
}
调整后的绘图位置(需要保存在
rotateAndCache
中):
mycontext.drawImage(rotobj,x-(diam-width)/2,y-(diam-height)/2);
    ,        这是不可能的,您可能不需要它。尝试这个:
context.save() // Save current state (includes transformations)
context.rotate()
... draw image ...
context.restore() // Restore state