Canvas DrawImage() poor quality [duplicate]

半城伤御伤魂 提交于 2021-02-04 13:20:15

问题


I have a problem with Html5 canvas

i draw an image but its quality becomes very poor enter image description here

after i draw it with canvas it becomes this

enter image description here

my code is 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:


enter image description here

You can incrementally scale your image down for better results.

Since your final size is 1/4 the original size, you could:

  • scale the 1000x669 image in half to 500x334 onto a temp canvas

  • scale the 500x335 canvas in half to 250x167 onto the main canvas

Here's example code and a Demo:

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);
}
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>


来源:https://stackoverflow.com/questions/28498014/canvas-drawimage-poor-quality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!