请看下面的例子:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
img = new Image();
img.onload = function(){
canvas.width = 400;
canvas.height = 150;
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, 400, 150);
}
img.src = "http://openwalls.com/image/1734/colored_lines_on_blue_background_1920x1200.jpg";
正如你所看到的,图像并不是抗锯齿的,尽管据说drawImage会自动应用抗锯齿。我尝试了许多不同的方法,但似乎不起作用。您能告诉我如何获得抗锯齿图像吗?谢谢。
发布于 2014-08-27 22:12:29
除了Ken的答案之外,这里还有另一个解决方案,将下采样分成两半执行(因此,使用浏览器的算法,结果看起来很好):
function resize_image( src, dst, type, quality ) {
var tmp = new Image(),
canvas, context, cW, cH;
type = type || 'image/jpeg';
quality = quality || 0.92;
cW = src.naturalWidth;
cH = src.naturalHeight;
tmp.src = src.src;
tmp.onload = function() {
canvas = document.createElement( 'canvas' );
cW /= 2;
cH /= 2;
if ( cW < src.width ) cW = src.width;
if ( cH < src.height ) cH = src.height;
canvas.width = cW;
canvas.height = cH;
context = canvas.getContext( '2d' );
context.drawImage( tmp, 0, 0, cW, cH );
dst.src = canvas.toDataURL( type, quality );
if ( cW <= src.width || cH <= src.height )
return;
tmp.src = dst.src;
}
}
// The images sent as parameters can be in the DOM or be image objects
resize_image( $( '#original' )[0], $( '#smaller' )[0] );
发布于 2014-04-23 22:25:02
var getBase64Image = function(img, quality) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
//----- origin draw ---
ctx.drawImage(img, 0, 0, img.width, img.height);
//------ reduced draw ---
var canvas2 = document.createElement("canvas");
canvas2.width = img.width * quality;
canvas2.height = img.height * quality;
var ctx2 = canvas2.getContext("2d");
ctx2.drawImage(canvas, 0, 0, img.width * quality, img.height * quality);
// -- back from reduced draw ---
ctx.drawImage(canvas2, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
// return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
https://stackoverflow.com/questions/17861447
复制相似问题