在Canvas中以角度绘制图像而不旋转画布 [英] Drawing image in Canvas at an angle WITHOUT rotating the Canvas

查看:667
本文介绍了在Canvas中以角度绘制图像而不旋转画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JavaScript中的画布在HTML 5中绘制图像。我需要以旋转的角度画出它。我知道这可以通过使用画布上下文应用旋转(角度)函数来完成。但是我必须在不旋转画布本身的情况下执行此操作 如果可能的话,请提供可能的解决方法。

实际上,您可以绘制任何想要旋转到屏幕外的画布并将其绘制到主画布中。我从Google IO Talk借用了这段代码:

  rotateAndCache = function(image,angle){
var offscreenCanvas =使用document.createElement( '画布');
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));

返回offscreenCanvas;
}

然后将其缓存:

  rotobj = rotateAndCache(myimg,myangle)

并在您的绘图代码中:

pre $ mycontext.drawImage(rotobj,x_coord,y_coord)

只有当一个对象只旋转了一次角度并且随后只进行转换时才有用。


I am drawing an image in HTML 5 using canvas in JavaScript. I need to draw it at a rotated angle. I know this can be done by applying rotate(angle) function using the context of the canvas. But I need to do this without rotating the canvas itself.

Kindly suggest possible approach for this if it's possible.

解决方案

You can actually draw whatever you want to rotate into an offscreen canvas and draw that into your main canvas. I borrowed this code from a 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;
}

then cache it with:

rotobj = rotateAndCache(myimg,myangle)

and in your drawcode:

mycontext.drawImage(rotobj,x_coord,y_coord)

This is only useful if you have an object that is rotated by an angle only once and is subsequently only subject to transformations.

这篇关于在Canvas中以角度绘制图像而不旋转画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆