【问题标题】:Resize canvas after scale image缩放图像后调整画布大小
【发布时间】:2013-11-03 08:05:04
【问题描述】:

我正在尝试缩放已经绘制到画布中的图像。我使用this answer 用于在画布中绘制/旋转图像。此示例对我来说工作正常并正确调整画布大小。我想使用缩放(放大/缩小)图像工作正常,但画布不能正确调整大小。 我想在缩放后根据图像大小调整画布大小。 这是示例代码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);

}

【问题讨论】:

    标签: jquery html html5-canvas


    【解决方案1】:

    您可以通过将画布大小乘以您的 currentScale 来调整画布大小:

    canvas.width = size.width*currentScale;
    canvas.height = size.height*currentScale;
    

    【讨论】:

    • +1。 OP:还考虑重构代码,因为现在您在同一个函数中混合大小和绘图:jsfiddle.net/AbdiasSoftware/6ZsCz/99
    • @Ken-Abdias 样品罐 :)
    • @MarkE 坦克快速回答:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2013-03-24
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多