我们如何灰度化画布中使用的图案图像(javascript)

时间:2017-11-11 18:55:52

标签: javascript canvas grayscale

创建了一个圆形上下文并添加了模式图像以填充该圆圈。我可以将该模式图像灰度化。 有什么想法可以帮助我。

代码:

Exception in thread "main" java.lang.NoClassDefFoundError: user/login/creation/UserValidation/AppTest
    at user.login.creation.UserValidation.App.main(App.java:12)
Caused by: java.lang.ClassNotFoundException: user.login.creation.UserValidation.AppTest
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

1 个答案:

答案 0 :(得分:0)

这可能不是最好的方法,但它非常简单且有效。

我在下面附上了一个工作示例。以下是它的工作原理:

图案图像是在不可见的画布中绘制的。加载图像后,将在画布上绘制图像,并将白色叠加和饱和度设置为全局复合操作。画布现在将包含图案的灰度版本。

然后将临时画布转换为图像,其源设置为画布数据URL。也许有更好的方式在两幅画布之间发送图像数据,但我还没找到。

模式完成后,将使用新模式绘制原始圆弧。



let canvas = document.getElementById('grayscale-canvas');
let ctx = canvas.getContext('2d');

function makeGrayscaleBackground(image, onready) {
  var bg = new Image();
  bg.src = image;
  bg.onload = function() {
    // Create a canvas that's not attached to the DOM
    var canvas = document.createElement('canvas');
    canvas.setAttribute('width', this.width);
    canvas.setAttribute('height', this.height);
    document.body.appendChild(canvas);
    let ctx = canvas.getContext('2d');

    // Draw the background image
    ctx.drawImage(this, 0, 0);

    // Then draw a white layer on top, with the saturation composite operation
    // which will remove the color from the underlying image
    ctx.globalCompositeOperation = "saturation";
    ctx.fillStyle = "#FFF";
    ctx.fillRect(0, 0, this.width, this.height);

    onready(canvas);
  };

}

function drawWithImage(image) {

  makeGrayscaleBackground(image, function(patternImage) {
    // Green background
    ctx.fillStyle = "#3f9";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Make a repeating pattern with image we created
    var pattern = ctx.createPattern(patternImage, "repeat");

    // Make an arc with the pattern
    let x = y = canvas.width/2;
    ctx.fillStyle = pattern;
    ctx.beginPath();
    ctx.arc(x, y, canvas.width/2-10, 0, 2*Math.PI);
    ctx.fill();
  })

}

// Example pattern image
// For security reasons, the image needs to be hosted on the same server as the script!
var bgImage = "data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7";
drawWithImage(bgImage);
document.getElementById('bg').src = bgImage;

<canvas width="150" height="150" id="grayscale-canvas"></canvas><br>
Actual background image: <img id="bg"><br>
Modified background image:
&#13;
&#13;
&#13;