【发布时间】:2015-05-07 01:49:53
【问题描述】:
我想在我的 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;
}
}
它适用于 Zoom + 但不适用于 Zoom -。
无论如何,我认为这不是我期望的最好方法,最好找到一种直接从Editor.data操作的方法,而不必每次都重置画布,或者保存Image对象. 另外,我不确定是否使用 scale 方法...
任何帮助将不胜感激
(对不起我的英语)
【问题讨论】:
标签: javascript html canvas zooming