在画布上下文旋转时,是否在默认画布上下文上绘制了在画布上进行的任何绘制?

时间:2019-06-09 14:16:57

标签: html html5-canvas

const ctx = canvas.getContext("2d")
var image = new Image();
image.src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/darwin300.jpg"

image.onload = function() {
    var maxsize = image.width;
    var w = maxsize;
    var ratio = (image.width / w);//1
    var h = (image.height / ratio);
    canvas.width = w;
    canvas.height = h;
    ctx.canvas.width = image.width;
    ctx.canvas.height = image.height;
    //c.width = image.width;
    //c.height = image.height;
    ctx.translate(w, h);
    ctx.rotate(Math.PI);
    ctx.drawImage(image,0,0,w,h);
    ctx.save();
    ctx.fillRect(0, 0, 150, 100);
    }
    
<canvas id="canvas"></canvas>

在下面的画布旋转功能上,所有上下文ctx绘图均以默认图像方向(右下角坐标(0,0))进行绘制。如何在旋转后的图像(0,0)上填充矩形?

2 个答案:

答案 0 :(得分:0)

对我有用。我刚刚注释掉

//c.width = image.width;
//c.height = image.height;

因为我不知道c是什么。

顺便说一句:您在该函数中没有使用过的代码。

const ctx = canvas.getContext("2d")


var image = new Image();
image.src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/darwin300.jpg"

image.onload = function() {
    var maxsize = image.width;
    var w = maxsize;
    var ratio = (image.width / w);//1
    var h = (image.height / ratio);
    canvas.width = w;
    canvas.height = h;
    ctx.canvas.width = image.width;
    ctx.canvas.height = image.height;
    //c.width = image.width;
    //c.height = image.height;
    
    ctx.save();
    
    ctx.translate(w, h);
    ctx.rotate(Math.PI);
    ctx.drawImage(image,0,0,w,h);
    
    ctx.restore();
    
    ctx.fillRect(0, 0, 150, 100);
    }
    
    
    
canvas{border:1px solid}
<canvas id="canvas"></canvas>

答案 1 :(得分:0)

要重置上下文的当前转换矩阵,可以使用setTransform方法和身份矩阵(1, 0, 0, 1, 0, 0

const ctx = canvas.getContext("2d")
var image = new Image();
image.src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/darwin300.jpg"

image.onload = function() {
  var maxsize = image.width;
  var w = maxsize;
  var ratio = (image.width / w); //1
  var h = (image.height / ratio);
  canvas.width = w;
  canvas.height = h;

  ctx.translate(w, h);
  ctx.rotate(Math.PI);
  ctx.drawImage(image, 0, 0, w, h);

  // reset the transform matrix
  ctx.setTransform(1, 0, 0, 1, 0, 0);

  ctx.fillRect(0, 0, 150, 100);
}
<canvas id="canvas"></canvas>

相关问题