실제로이 효과는 canvas pixel manipulation을 통해 얻을 수 있지만 다른 사용자는 이미지 편집 프로그램을 통해 이미지를 투명하게 만드는 것이 더 간단 할 것이라고 말했습니다.
나는 fiddle here에서 이것을 달성하는 방법의 예를 만들었습니다.
이 코드가 처음 수행하는 것은 이미지 요소 <img id="code" src="url.png">
을 검색하고 캔버스 개체를 구성하고 context.drawImage
호출을 통해 이미지의 내용을 캔버스에 그립니다.
// Get the image element.
var el = document.getElementById('code');
// Create a canvas and set its width and height.
var canvas = document.createElement('canvas');
canvas.setAttribute('width', 250);
canvas.setAttribute('height', 250);
// Get the canvas drawing context, and draw the image to it.
var context = canvas.getContext('2d');
context.drawImage(el, 0, 0, canvas.width, canvas.height);
다음,
// Get the canvas image data.
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
// Create a function for preserving a specified colour.
var preserveColor = function(imageData, color) {
// Get the pixel data from the source.
var data = imageData.data;
// Iterate through all the pixels.
for (var i = 0; i < data.length; i += 4) {
// Check if the current pixel should have preserved transparency. This simply compares whether the color we passed in is equivalent to our pixel data.
var preserve = data[i] === color.r
&& data[i + 1] === color.g
&& data[i + 2] === color.b
&& data[i + 3] === color.a;
// Either preserve the initial transparency or set the transparency to 0.
data[i + 3] = preserve ? data[i + 3] : 0;
}
return imageData;
};
// Get the new pixel data and set it to the canvas context.
var newData = preserveColor(imageData, {r: 255, g: 255, b: 255, a: 255});
context.putImageData(newData, 0, 0);
마지막으로, 우리는 document.body.appendChild(canvas);
를 사용하여 우리의 페이지에 요소를 추가 할 수 있습니다. 또는 원본 이미지 요소를 캔버스로 완전히 대체 할 수 있습니다.
분명히 픽셀 데이터 반복은 매우 느릴 수 있고 큰 이미지 크기로만 증가하기 때문에 이것은 이상적인 솔루션이 아닙니다. preserveColor
기능을 쉽게 변경하여 지정된 색이 투명 해지는 makeTransparent
과 반대로 수행 할 수도 있습니다. 그러나 이렇게하려면 지정한 색상과 비슷한 색상의 논리가 약간 더 필요합니다.또는 이것을 셰이더 (shader)로 구현하여 CPU 대신 GPU로 이동하여 처리가보다 효율적으로 수행되도록 할 수 있습니다.
QR 코드를 투명 PNG로 변환하십시오. 검은 색 값의 알파 값이 0 인 경우 – evolutionxbox