0
我想縮放已經被繪製到canvas中的圖像。我使用this answer 在canvas中繪製/旋轉圖像。此示例對我很好,並且正確調整了Canvas的大小。我想要使用縮放(ZoomIn/ZoomOut)圖像工作正常,但畫布無法正確調整大小。 我想在縮放後根據圖像大小調整畫布大小。 下面是示例代碼http://jsfiddle.net/6ZsCz/97/在縮放圖像後調整畫布大小
var zoomDelta = 0.1;
var currentScale = 1;
var ctx = canvas.getContext("2d");
var imgWidth;
var imgHeight;
var size = {};
var rotation = 0;
img = new Image();
img.onload = function() {
rotation = 0;
imgWidth = img.width;
imgHeight = img.height;
size = {
width: imgWidth,
height: imgHeight
};
draw();
newSize(imgWidth, imgHeight, rotation);
};
$("#zoomOut").click(function() {
currentScale -= zoomDelta;
draw();
newSize(imgWidth/currentScale, imgHeight/currentScale, rotation);
});
function draw() {
canvas.width = size.width;
canvas.height = size.height;
var cx = canvas.width/2;
var cy = canvas.height/2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(cx, cy);
ctx.scale(currentScale, currentScale);
ctx.rotate(rotation * deg2Rad);
ctx.drawImage(img, (-imgWidth/2) , (-imgHeight/2));
}
function newSize(w, h, a) {
var rads = a * Math.PI/180;
var c = Math.cos(rads);
var s = Math.sin(rads);
if (s < 0) {
s = -s;
}
if (c < 0) {
c = -c;
}
size.width = (h * s + w * c) ;
size.height = (h * c + w * s);
}
+1。 OP:同時考慮重新考慮代碼,因爲現在您正在使用相同的函數來混合大小和繪圖:http://jsfiddle.net/AbdiasSoftware/6ZsCz/99/ – K3N
@ Ken-Abdias坦克用於示例:) – ZSH
@MarkE坦克快速回答:D – ZSH