无法获取context.rotate以正确显示图像

时间:2017-06-09 14:41:38

标签: html5-canvas

我需要将图像旋转180度,但是当我添加旋转代码时,图像变成正方形。

var moulding_matte_canvas_height = [],
  canvas = document.createElement('canvas'),
  ctx = canvas.getContext("2d"),
  width = 5.171363636363637,
  opening_i = 0,
  rotate = 180 * Math.PI / 180,
  i = 2;

moulding_matte_canvas_height[0] = 225;
canvas.width = 285;
canvas.height = 335;
img = new Image();
img.src = 'http://www.asa.tframes.org:1881/system/components/compimg/80ac89fad42cf14561b641df241bf406/pattern';

function moulding_get_segment_width(img_width, opening_i)
{
  return 175;
}

//
$(img).on("load", function() {
ctx.save(); 
ctx.translate(width, moulding_matte_canvas_height[opening_i]); 
//ctx.rotate(rotate);
//ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, moulding_get_segment_width(img.width, i), width);
ctx.restore();   

//
});
$("#mattes").append(canvas); /*appending the canvas*/

http://fiddle.jshell.net/onpa628e/1/

(空白是故意的,因为其他元素将会被绘制,而图像旁边的红色只是为了清晰起见)

不旋转:

enter image description here

旋转: enter image description here

预期: enter image description here

1 个答案:

答案 0 :(得分:0)

您的图片看起来像一个正方形,因为它只显示画布上的一小部分。发生这种情况是因为translate仅在x轴上移动~5px(您的“width”变量)。

Here's your example modified x值较高。