gpt4 book ai didi

javascript - 我们如何对 Canvas 中使用的图案图像进行灰度化(javascript)

转载 作者:行者123 更新时间:2023-11-29 23:31:20 26 4
gpt4 key购买 nike

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

代码:

    ctx.beginPath();
var bg = new Image();
bg.src = image;
bg = function() {
var pattern = ctx.createPattern(this, "no-repeat");
ctx.fillStyle = pattern;
};
ctx.moveTo(canvasCenterHoriz, canvasCenterVert);
ctx.arc(x, y, radius, startAngle, endAngle, direction);
ctx.lineWidth = 0;
ctx.fill();

最佳答案

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

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

图案图像绘制在不可见的 Canvas 中。加载图像后,它被绘制在 Canvas 上,白色覆盖和饱和度设置为全局合成操作。 Canvas 现在将包含您的图案的灰度版本。

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

图案完成后,您的原始圆弧将使用新图案绘制。

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:

关于javascript - 我们如何对 Canvas 中使用的图案图像进行灰度化(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com