在两个画布之间复制会导致模糊

时间:2017-11-03 16:39:08

标签: javascript html5 canvas

我有两幅画布。当我使用max.getKey()从一个画布复制到另一个画布时,它会略微模糊图像。

为什么会这样?

这似乎是当某些子像素四舍五入时发生的事情。也许这是由45度'旋转'引起的?

以下是一个显示它的例子:

var input = "How much money has Rebecca Black made off of Friday?";
var mask = [{
   offset: 19,
   length: 13
 }, {
   offset: 25,
   length: 6
}];

function replaceMask(input, mask){
  var result = "";
 for(var i = 0; i < input.length; i++){
  if(mask.find(rule => i > rule.offset && i < (rule.offset + rule.length))){
    result += "X";
  }else{
   result += input[i];
  }
 }
 return result;
}

console.log(replaceMask(input, mask));
drawImage()
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var tempCanvas = document.getElementById("tmpCanvas");
var tempCtx = tempCanvas.getContext("2d");

canvas.width = canvas.height = 200;
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;

// translate origins
ctx.translate(canvas.width / 2, canvas.height / 2);
tempCtx.translate(canvas.width / 2, canvas.height / 2);

// Create a red square
ctx.fillStyle = "rgba(255,0,0, 0.1)";
ctx.fillRect(-50, -50, 100, 100);

var angle = 0;

// Each draw we copy the current canvas to the tmpCanvas. Then copy it back to the original canvas.
function draw() {
  angle += 45;

  tempCtx.save();
  tempCtx.rotate(angle * Math.PI / 180);
  tempCtx.drawImage(
    canvas,
    0, // sourceX
    0, // sourceY - note that source ignores translation. It's not a canvas context, so we choose top left corner of the canvas to start copying pixels.
    canvas.width, // sourceWidth
    canvas.height, // sourceHeight
    -0.5 * canvas.width, // destinationX
    -0.5 * canvas.height, // destinationY
    canvas.width, // destinationWidth
    canvas.height // destinationHeight
  );
  tempCtx.restore();

  ctx.drawImage(
    tempCanvas,
    0,
    0,
    canvas.width,
    canvas.height,
    -0.5 * canvas.width,
    -0.5 * canvas.height,
    canvas.width,
    canvas.height
  );

  // requestAnimationFrame(draw);
}

document.addEventListener("click", draw);

1 个答案:

答案 0 :(得分:1)

这只是在行动中的抗锯齿。当旋转两度45度时,防眩边缘会略微落在原方形外面,随着时间的推移,这些边缘会增加。

  

我的目标是制作一个画布,您可以在其上绘制,因为现有内容围绕原点旋转。

您可以在原始画布上进行绘制操作(将反向旋转应用于鼠标的位置),然后重复绘制旋转到输出画布的原始画布。数据只在一个方向上流动,从原始方向流向输出方向,所以没有退化。