缩放图像后调整画布大小 [英] Resize canvas after scale image

查看:143
本文介绍了缩放图像后调整画布大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试缩放已经绘制到画布中的图像.我使用这个答案 用于在画布中绘制/旋转图像.此示例对我来说很好,可以正确调整画布的大小.我想使用scale(ZoomIn/ZoomOut)一个imag工作得很好,但画布无法正确调整大小. 我想在缩放后根据图像大小调整画布大小. 这是示例代码 http://jsfiddle.net/6ZsCz/97/

I'm trying to scale an image that has already been draw into canvas.I using this answer for draw/rotate image in canvas.This sample work fine for me and resize canvase correctly .I want use scale(ZoomIn/ZoomOut) an imag work fine but canvas not resize correctly. I want resize canvas base on image size after scale. Here is example code 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);

}

推荐答案

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

You can resize then canvas to scale by multiplying the canvas size by your currentScale:

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

这篇关于缩放图像后调整画布大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆