Resize a HTML 5 canvas and its content in pure Jav

2019-01-29 02:06发布

问题:

I would like to implement a "zoom" function in my Web App to resize a canvas and its content proportionally (I don't care about dirty quality).

Here's my code. It resets the canvas each time we want to zoom in order to get an Image object (for using drawImage method), resize the canvas, and then use drawImage method to resize content proportionally...

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;
    }
}

It works for Zoom + but not for Zoom -.

Anyway, I don't think it's the best way to do what I expect, it would be better to find a way to operate directly from Editor.data, without having to reset the canvas each time, or saving the Image object. In addition, I'm not sure about using scale method...

Any help would be appreciated

(Sorry about my english)

回答1:

Try utilizing <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 />