我正在使用Javascript开发一个玩具项目。目标是拥有两个不同尺寸的不同画布元素。我想在浏览器中显示一个较小的图像,用户可以在其上应用效果,当保存时,更改将应用于较大的图像。
基本上,我的工作流程是
FileReader.onload
回调originalCanvas
和previewCanvas
previewCanvas
调整宽高比以适合预览容器我的问题是缩小操作会导致裁剪,而不是调整大小。
我的代码是
//executes on the drop event
var reader = new FileReader();
reader.onload = function(e){
canvasImage = new ImageWrapper();
canvasImage.init(e.target.result, "preview", "center_align");
canvasImage.scaleAspect("image_preview");
document.getElementById("drop_image_container")
.appendChild(canvasImage.previewCanvas.canvas);
我创建了一个ImageWrapper
对象来包含几个字段:
var ImageWrapper = function(){
//set up the original and preview canvases
var originalCanvas = new CanvasImage(),
previewCanvas = new CanvasImage();
//inner object to allow for original and preview canvas objects.
function CanvasImage(){
var canvas = document.createElement("canvas"),
context = canvas.getContext("2d"),
image = new Image();
return {
canvas : canvas,
context : context,
image : image
};
}
function init(src, id, classes){
previewCanvas.canvas.id = id;
previewCanvas.canvas.className = classes;
originalCanvas.image.src = src;
previewCanvas.image.src = src;
originalCanvas.canvas.height = originalCanvas.image.naturalHeight;
originalCanvas.canvas.width = originalCanvas.image.naturalWidth;
previewCanvas.canvas.height = previewCanvas.image.naturalHeight;
previewCanvas.canvas.width = previewCanvas.image.naturalWidth;
previewCanvas.image.onload = function(){
previewCanvas.context.drawImage(previewCanvas.image, 0, 0);
originalCanvas.context.drawImage(originalCanvas.image, 0, 0);
}
}
init()
函数用于创建具有默认图像大小的两个画布元素。然后使用预览容器的id调用scaleAspect()
,这允许我在保持宽高比的同时计算画布的新尺寸。
/* Scales the canvas element while maintaining aspect ratio of the original
*/
function scaleAspect(previewContainer){
var container = processParam(previewContainer),
width = previewCanvas.canvas.width,
height = previewCanvas.canvas.height;
var ratio = [container.width()/width, container.height()/height];
ratio = Math.min(ratio[0], ratio[1]);
previewCanvas.canvas.width = width * ratio;
previewCanvas.canvas.height = height * ratio;
previewCanvas.context.drawImage(previewCanvas.image, 0, 0,
previewCanvas.canvas.width, previewCanvas.canvas.height);
}
完成此功能后,previewCanvas.canvas
元素将作为删除容器的子项添加。
此drawImage正在执行,但结果并非我所期望的。预览容器为500x500像素,这使得新图像的大小为375x500像素。这个drawImage正在执行裁剪操作,尽管执行时有一个闪烁。我可以在裁剪设置之前简要地看到调整大小的图像。
是否可能正在绘制originalCanvas
元素,即使它未绑定到元素?
答案 0 :(得分:1)
您使用的drawImage(image, x, y)版本将在画布上以原始像素大小绘制图像。相反,您应该使用drawImage(image, x, y, width, height)版本,该版本允许您在将图像绘制到画布时指定目标大小。