调整 HTML 5 canvas 及其内容的大小 Javascript

Resize a HTML 5 canvas and its content in pure Javascript

我想在我的 Web 应用程序中实现一个 "zoom" 函数来按比例调整 canvas 及其内容的大小(我不关心肮脏的质量)。

这是我的代码。每次我们想要缩放时它都会重置 canvas 以获得 Image 对象(使用 drawImage 方法),调整 canvas 的大小,然后使用 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;
    }
}

它适用于 Zoom + 但不适用于 Zoom -。

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

如有任何帮助,我们将不胜感激

(对不起我的英文)

尝试利用 <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 />