首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用javascript画布调整图像大小(平滑)

使用javascript画布调整图像大小(平滑)
EN

Stack Overflow用户
提问于 2013-10-09 10:41:25
回答 8查看 324.1K关注 0票数 122

我正在尝试用画布调整一些图像的大小,但我不知道如何平滑它们。在photoshop、浏览器等上。有一些他们使用的算法(例如双三次,双线性),但我不知道这些算法是否内置到画布中。

这是我的小提琴:http://jsfiddle.net/EWupT/

代码语言:javascript
复制
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);

第一个是一个普通的调整大小的图像标签,第二个是画布。请注意画布是如何不那么平滑的。我怎样才能达到“流畅”?

EN

回答 8

Stack Overflow用户

发布于 2016-09-22 19:31:42

因为Trung Le Nguyen Nhat's fiddle根本不正确(它在最后一步中只使用了原始图像)

我写了我自己的关于性能比较的小提琴:

FIDDLE

基本上就是:

代码语言:javascript
复制
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);
}
票数 51
EN

Stack Overflow用户

发布于 2014-09-17 07:34:43

我创建了一个可重用的Angular服务,为感兴趣的任何人处理高质量的图像/画布大小调整:https://gist.github.com/transitive-bullshit/37bac5e741eaec60e983

该服务包括两种解决方案,因为它们都有自己的优缺点。lanczos卷积方法以更慢为代价获得更高的质量,而逐步向下缩放方法产生合理的抗锯齿结果,并且速度明显更快。

示例用法:

代码语言:javascript
复制
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
    })
})
票数 17
EN

Stack Overflow用户

发布于 2020-04-17 04:40:58

我不明白为什么没有人建议使用createImageBitmap

代码语言:javascript
复制
createImageBitmap(
    document.getElementById('image'), 
    { resizeWidth: 300, resizeHeight: 234, resizeQuality: 'high' }
)
.then(imageBitmap => 
    document.getElementById('canvas').getContext('2d').drawImage(imageBitmap, 0, 0)
);

效果很好(假设您为image和canvas设置了ids )。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19262141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档