我正在尝试使用html5画布创建一个简单的拖放编辑器,用于制作带印花的T恤样机。我遇到的问题是,一旦我旋转一个图像,旋转时是一个带背景图像的简单div,我尝试在画布上绘制它,依靠这个div的位置和旋转并观察脱位取决于角度。
如果角度为0度,则绘制的图像没有任何错位,与div的位置相比较。
但是,如果旋转与0不同,则位置会发生变化。
这是代码,绘图打印,存储为对象,基于drag'n'drop div的大小,位置和旋转。
load_print: function(callback) {
var self = this;
if (this.Drag._clone === null) return;
var img = new Image();
img.onload = function() {
var width = self.Drag._clone.width();
var height = width * img.height / img.width;
var rotate = parseFloat(self.Drag._clone.attr('rotate')) || 0;
var left = self.Drag._clone.get(0).getBoundingClientRect().left -
self._print_canvas.getBoundingClientRect().left;
var top = self.Drag._clone.get(0).getBoundingClientRect().top -
self._print_canvas.getBoundingClientRect().top;
self.save_print(img, left, top, width, height, rotate);
return (typeof callback === 'function' ? callback() : null);
};
img.src = this.Drag._clone.css('background-image').replace('url("','').replace('")','');
},
save_print: function(img, left, top, width, height, rotate) {
console.log(left, top);
this._prints_arr.push({
img: img,
left: left,
top: top,
width: width,
height: height,
rotate: rotate
});
},
draw_prints: function() {
console.log('drawing');
this.Drag.destroy();
this._print_canvas_ctx.clearRect(
0,
0,
this._print_canvas.width,
this._print_canvas.height
);
for (var i in this._prints_arr) {
this._print_canvas_ctx.save();
this._print_canvas_ctx.setTransform(1,0,0,1,0,0);
this._print_canvas_ctx.translate(
this._prints_arr[i].left + this._prints_arr[i].width / 2,
this._prints_arr[i].top + this._prints_arr[i].height / 2
);
this._print_canvas_ctx.rotate(this._prints_arr[i].rotate);
this._print_canvas_ctx.drawImage(
this._prints_arr[i].img,
-this._prints_arr[i].width / 2,
-this._prints_arr[i].height / 2,
this._prints_arr[i].width,
this._prints_arr[i].height
);
this._print_canvas_ctx.restore();
}
},
如何修复旋转图像在画布上的定位?