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)