提问人:Aviato 提问时间:10/10/2023 最后编辑:Aviato 更新时间:10/11/2023 访问量:40
如何应用“混合混合模式:亮度”;HTML5 Canvas 中的效果
How to Apply 'mix-blend-mode: luminosity;' Effects in HTML5 Canvas
问:
我正在做一个涉及 HTML5 Canvas 的项目,我想在 Canvas 中复制 CSS“混合-混合模式:亮度”和“背景-滤镜”效果。虽然我已经找到了有关将背景效果应用于 Canvas 的信息,但我现在正在寻找有关如何实现“混合-混合模式:亮度”滤镜效果的指导。任何人都可以提供有关如何将这两种效果应用于 Canvas 绘图或图像的全面解释或代码示例吗?您的见解将不胜感激!
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = draw;
img.setAttribute('crossOrigin', '');
img.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
function draw() {
canvas.width = img.width;
canvas.height = img.height;
// Draw the image onto the canvas
ctx.drawImage(img, 0, 0);
// Define the coordinates and dimensions of the rectangle
const rectX = 100; // X-coordinate of the top-left corner of the rectangle
const rectY = 100; // Y-coordinate of the top-left corner of the rectangle
const rectWidth = 200; // Width of the rectangle
const rectHeight = 150; // Height of the rectangle
// Get the pixel data of the canvas
const imageData = ctx.getImageData(rectX, rectY, rectWidth, rectHeight);
const pixels = imageData.data;
// Apply 'mix-blend-mode: luminosity;' manually to the rectangle
for (let i = 0; i < pixels.length; i += 4) {
// Calculate the luminance of the current pixel
const luminance = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3;
// Set the RGB values of the pixel to the luminance value
pixels[i] = luminance;
pixels[i + 1] = luminance;
pixels[i + 2] = luminance;
}
// Put the modified pixel data back onto the canvas at the same position
ctx.putImageData(imageData, rectX, rectY);
// Draw the rectangle with the luminance effect
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'; // Red color with 50% opacity
ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
}
<canvas id="canvas"></canvas>
答: 暂无答案
评论
globalCompositeOperation