画布DrawImage()质量差

时间:2015-02-13 10:56:57

标签: javascript html5 canvas

我的Html5画布有问题

我画了一张图片,但质量却很差 enter image description here

用画布绘制之后就变成了这个

enter image description here

我的代码在这里

<script type="text/javascript">

$canvasWidth = $('#canvas').width;
$canvasHeight = $('#canvas').height;
var alpha = 0.0;

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');


function draw(){
    var delta = 0.05;
    ctx.clearRect(0,0,$canvasWidth, $canvasHeight);
    ctx.globalAlpha = alpha;

    var logo= new Image();

    WandioLight.onload = function(){
        ctx.drawImage(logo, 0, 0, 250, 167);

    };

    logo.src = "logo.png";

    alpha += delta;
    if(alpha > 1.0){
        return false;
    }
    setTimeout(draw, 50);
}

1 个答案:

答案 0 :(得分:8)

enter image description here

您可以逐步缩小图像以获得更好的效果。

由于您的最终尺寸是原始尺寸的1/4,您可以:

  • 将1000x669图像的一半缩放为500x334到临时画布上

  • 将500x335画布的一半缩放为250x167到主画布上

以下是示例代码和演示:

&#13;
&#13;
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/wandio.png";
function start(){


  // scale the 1000x669 image in half to 500x334 onto a temp canvas
  var c1=scaleIt(img,0.50);

  // scale the 500x335 canvas in half to 250x167 onto the main canvas
  canvas.width=c1.width/2;
  canvas.height=c1.height/2;
  ctx.drawImage(c1,0,0,250,167);

}

function scaleIt(source,scaleFactor){
  var c=document.createElement('canvas');
  var ctx=c.getContext('2d');
  var w=source.width*scaleFactor;
  var h=source.height*scaleFactor;
  c.width=w;
  c.height=h;
  ctx.drawImage(source,0,0,w,h);
  return(c);
}
&#13;
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;