在纯Javascript中调整HTML 5画布及其内容的大小

时间:2015-03-05 15:56:34

标签: javascript html5 canvas zoom

我想在我的Web应用程序中实现“缩放”功能,以按比例调整画布及其内容(我不关心脏质)。

这是我的代码。每次我们想要缩放时都会重置画布以获取Image对象(使用drawImage方法),调整画布大小,然后使用drawImage方法按比例调整内容...

var Editor = {
    // The following variables contains informations
    // about the original canvas
    data: ..., // imageData
    width: 200,
    height: 50,

    // Zoom canvas
    zoomCanvas: function(zoom){ // zoom in percents
        var canvas = $('#canvas').get(0);
        var context = canvas.getContext();
        var data = this.data;
        var scale = zoom / 100;
        var width = this.width * scale;
        var height = this.height * scale;

        // Reset canvas to original size and imageData
        this.resizeCanvas(this.width, this.height); 
        context.scale(1, 1);
        context.putImageData(data, 0, 0);

        // Get Image from original canvas data
        var url = canvas.toDataURL();
        var img = $('<img src="' + url + '">').get(0);

        // Resize canvas, apply scale and draw Image with new proportions
        this.resizeCanvas(width, height);
        context.scale(scale, scale);
        context.drawImage(img, 0, 0);
    },

    // Resize canvas
    resizeCanvas: function(width, height){
        // NOTE : I don't know exactly how to resize it so...
        var canvas = $('#canvas').get(0);
        canvas.width = width;
        canvas.height = height;
        $(canvas).width(width).attr('width', width);
        $(canvas).height(height).attr('height', height);

        var context = canvas.getContext('2d');
        context.width = width;
        context.height = height;
    }
}

适用于缩放+但不适用于缩放 - 。

无论如何,我认为这不是我期望的最佳方式,最好找到一种直接从Editor.data操作的方法,而不必每次都重置画布,或者保存Image对象。 另外,我不确定使用比例法...

任何帮助将不胜感激

(抱歉我的英文)

1 个答案:

答案 0 :(得分:1)

尝试使用<input type="range">transform: scale(sx[, sy])

var canvas = document.querySelectorAll("canvas")[0]
, scale = document.getElementById("scale");

scale.addEventListener("change", function(e) {
  canvas.style.transform = "scale(" 
  + e.target.value 
  + ","      
  + e.target.value 
  + ")"
})
body {
  height:800px;
}

canvas {
  background:blue;
  position:relative;
  display:block;
}

#scale {
  position:relative;
  display:inline-block;
  padding:8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="scale" type="range" min="0" max="2" step="0.1" value=""/><br /><br /><br /><br /><br /><br /><br />
<canvas width="200" height="200"></canvas><br />