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)上填充矩形?
答案 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>