HTML画布最小图像调整大小会导致图像失真

时间:2015-12-28 11:37:56

标签: canvas svg image-resizing

我有一个带有调整大小图像的html画布。图像大小从10-40%调整大小,如果您将图像调整大小超过50%,这应该不会有问题。

然而,图像最终扭曲了。

enter image description here

为了便于说明,上面的图像放大了几次。

第一张图片是调整大小的结果,第二张图片是图片的外观。我的第一个想法是创建SVG图像,但在未调整大小时它们甚至不显示正确。我猜帆布不会很好地支持SVG。

我创建了jsfidle示例link(注意左上角)

有没有办法正确调整图像大小,还是应该在photoshop中为每一个调整大小?

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

// širina canvasa
 ctx.canvas.width  = window.innerWidth-23;
 ctx.canvas.height = 80;


ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle="#b0b0b0";
ctx.fill();

  // resized image - wwrong
  var imgorg = new Image();
    imgorg.onload = function() {
    ctx.drawImage(imgorg,0, 10,30,30);
    }
     imgorg.src = 'http://vetercek.com/master3/img/vanish/50/v0.png';

// how the image should look like
  var imgorg2 = new Image();
    imgorg2.onload = function() {
    ctx.drawImage(imgorg2,0, 30);
    }
     imgorg2.src = 'http://vetercek.com/master3/img/vanish/30/v0.png';

 // SVG sample without resize   - also wrong
  var imgorg3 = new Image();
    imgorg3.onload = function() {
    ctx.drawImage(imgorg3,0, 60);
    }
     imgorg3.src = 'http://vetercek.com/master3/img/vanish/30/v0.svg';  

1 个答案:

答案 0 :(得分:0)

事实证明,画布中的绘图对象是正确的选择。它可以是动态的"调整大小"所以没有质量损失。对象首先绘制到隐藏的画布,然后绘制在可见的画布上。

https://jsfiddle.net/5xy2mLrp/11/

//magnification
var pov=0.2;

// znak1
var canvasPattern = document.createElement("canvas");
canvasPattern.width = 200*pov;canvasPattern.height = 200*pov;
var contextPattern = canvasPattern.getContext("2d");

// sign1
contextPattern.beginPath();
contextPattern.moveTo(95*pov,61.5*pov); contextPattern.lineTo(95*pov,138.5*pov);contextPattern.closePath();
contextPattern.lineWidth=2*pov;contextPattern.strokeStyle = 'black';contextPattern.stroke();
contextPattern.beginPath();
contextPattern.moveTo(98*pov,61.5*pov); contextPattern.lineTo(98*pov,138.5*pov);contextPattern.closePath();
contextPattern.lineWidth=4*pov;contextPattern.strokeStyle = 'white';contextPattern.stroke(); contextPattern.beginPath();
contextPattern.moveTo(100*pov,61.5*pov);contextPattern.lineTo(100*pov,138.5*pov);contextPattern.closePath();
contextPattern.lineWidth=2*pov;contextPattern.strokeStyle = 'black';contextPattern.stroke();


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

// širina canvasa
 ctx.canvas.width  = window.innerWidth-23;
 ctx.canvas.height = 80;


ctx.rect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.fillStyle="#808080";
ctx.fill();


ctx.drawImage(canvasPattern,30, 30);