使用javascript畫布調整圖像大?。樌┪以噲D用帆布調整一些圖像的大小,但我對如何平滑它們毫無頭緒。在Photoshop,瀏覽器等..他們使用了一些算法(例如雙三次,雙線性)但我不知道它們是否內置于畫布中。這是我的小提琴:http://jsfiddle.net/EWupT/var canvas = document.createElement('canvas');var ctx = canvas.getContext('2d');canvas.width=300canvas.height=234ctx.drawImage(img, 0, 0, 300, 234);document.body.appendChild(canvas);第一個是普通的已調整大小的圖像標記,第二個是畫布。請注意畫布如何不那么平滑。我怎樣才能實現'順暢'?
3 回答

HUWWW
TA貢獻1874條經驗 獲得超12個贊
由于Trung Le Nguyen Nhat的小提琴根本不正確(它只是在最后一步使用了原始圖像),
我寫了自己的一般小提琴,進行了性能比較:
基本上它是:
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);}