如何在HTML5画布中正确应用“乘法”色调到图像?

时间:2017-03-29 04:46:54

标签: javascript html5-canvas

我正在使用multiply属性的globalCompositeOperation值将色调应用于图像的剪切区域。它有效,但图像的下边缘有时会出现白色边框。

// Code goes here

document.addEventListener("DOMContentLoaded", function() {

  var canvas = document.getElementById('myCanvas');

  var img = new Image();
  img.onload = function() {

    render();

  }

  img.src = 'http://i.imgur.com/qiJkgK9.jpg';

  function render() {

    canvas.width = img.width * 2;
    canvas.height = img.height * 2;

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

    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

    ctx.save();
    ctx.beginPath();

    ctx.rect(200, 200, 200, 200);
    ctx.clip();

    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fill();

    ctx.restore();

    ctx.save();
    ctx.beginPath();

    ctx.rect(300, 100, 200, 200);
    ctx.clip();

    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fill();

    ctx.restore();

  }

});
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>
  <canvas id="myCanvas"></canvas>
</body>

</html>

如何防止边框出现或是否有更好的方法将multiply色调应用于图像?

1 个答案:

答案 0 :(得分:0)

您只需将fillRect用于您要查找的确切矩形,而不是clipfill,这会导致剪裁问题。

  var canvas = document.getElementById('myCanvas');
  function render() {
    canvas.width = img.width * 2;
    canvas.height = img.height * 2;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    ctx.globalCompositeOperation = 'multiply';
    ctx.fillStyle = 'red';
    ctx.fillRect(200, 200, 200, 200);
    ctx.fillRect(300, 100, 200, 200);
  }

  var img = new Image();
  img.onload = render;
  img.src = 'http://i.imgur.com/qiJkgK9.jpg';
<canvas id="myCanvas"></canvas>