在Canvas中以一定角度绘制图像而不旋转画布

Vin*_*yak 10 html javascript html5

我正在使用JavaScript中的canvas在HTML 5中绘制图像.我需要以旋转角度绘制它.我知道这可以通过使用画布的上下文应用旋转(角度)函数来完成.但我需要在不旋转画布的情况下这样做.

如果可能的话,请建议可行的方法.

Pet*_*erT 8

您实际上可以将任何想要旋转的内容绘制到屏幕外的画布上并将其绘制到主画布中.我从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;
}
Run Code Online (Sandbox Code Playgroud)

然后缓存它:

rotobj = rotateAndCache(myimg,myangle)
Run Code Online (Sandbox Code Playgroud)

在你的drawcode中:

mycontext.drawImage(rotobj,x_coord,y_coord)
Run Code Online (Sandbox Code Playgroud)

仅当您的对象仅旋转一个角度一次并且随后仅受到变换时,此选项才有用.