我正在尝试用画布调整一些图像的大小,但我不知道如何平滑它们。在photoshop、浏览器等上。有一些他们使用的算法(例如双三次,双线性),但我不知道这些算法是否内置到画布中。
这是我的小提琴:http://jsfiddle.net/EWupT/
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300
canvas.height=234
ctx.drawImage(img, 0, 0, 300, 234);
document.body.appendChild(canvas);
第一个是一个普通的调整大小的图像标签,第二个是画布。请注意画布是如何不那么平滑的。我怎样才能达到“流畅”?
发布于 2016-09-22 19:31:42
因为Trung Le Nguyen Nhat's fiddle根本不正确(它在最后一步中只使用了原始图像)
我写了我自己的关于性能比较的小提琴:
基本上就是:
img.onload = function() {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d"),
oc = document.createElement('canvas'),
octx = oc.getContext('2d');
canvas.width = width; // destination canvas size
canvas.height = canvas.width * img.height / img.width;
var cur = {
width: Math.floor(img.width * 0.5),
height: Math.floor(img.height * 0.5)
}
oc.width = cur.width;
oc.height = cur.height;
octx.drawImage(img, 0, 0, cur.width, cur.height);
while (cur.width * 0.5 > width) {
cur = {
width: Math.floor(cur.width * 0.5),
height: Math.floor(cur.height * 0.5)
};
octx.drawImage(oc, 0, 0, cur.width * 2, cur.height * 2, 0, 0, cur.width, cur.height);
}
ctx.drawImage(oc, 0, 0, cur.width, cur.height, 0, 0, canvas.width, canvas.height);
}
发布于 2014-09-17 07:34:43
我创建了一个可重用的Angular服务,为感兴趣的任何人处理高质量的图像/画布大小调整:https://gist.github.com/transitive-bullshit/37bac5e741eaec60e983
该服务包括两种解决方案,因为它们都有自己的优缺点。lanczos卷积方法以更慢为代价获得更高的质量,而逐步向下缩放方法产生合理的抗锯齿结果,并且速度明显更快。
示例用法:
angular.module('demo').controller('ExampleCtrl', function (imageService) {
// EXAMPLE USAGE
// NOTE: it's bad practice to access the DOM inside a controller,
// but this is just to show the example usage.
// resize by lanczos-sinc filter
imageService.resize($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
// resize by stepping down image size in increments of 2x
imageService.resizeStep($('#myimg')[0], 256, 256)
.then(function (resizedImage) {
// do something with resized image
})
})
发布于 2020-04-17 04:40:58
我不明白为什么没有人建议使用createImageBitmap
。
createImageBitmap(
document.getElementById('image'),
{ resizeWidth: 300, resizeHeight: 234, resizeQuality: 'high' }
)
.then(imageBitmap =>
document.getElementById('canvas').getContext('2d').drawImage(imageBitmap, 0, 0)
);
效果很好(假设您为image和canvas设置了ids )。
https://stackoverflow.com/questions/19262141
复制相似问题