캔버스로 초상화에 마스크를 적용하는 방법
9520 단어 webdevcanvasjavascript
const maskedImageBase64 = await maskPhoto(maskPhotoUrl, originalPhotoUrl)
/**
* Url to HTMLImageElement
* @param {string} url: image url
* @returns {Promise<HTMLImageElement>} HTMLImageElement
*/
export function urlToImageElement(url: string) {
return new Promise<HTMLImageElement>((resolve, reject) => {
const img = new Image()
img.crossOrigin = "anonymous";
img.src = url
img.onload = () => resolve(img)
img.onerror = reject
})
}
/**
* mask.jpg + original.jpg => masked.jpg
* @param {string} maskImageUrl: mask image url
* @param {string} originalImageUrl: original image url
* @returns {Promise<string | undefined>} masked image url(base64)
*/
export async function maskPhoto(maskImageUrl:string, originalImageUrl:string) {
try {
const maskImage = await urlToImageElement(maskImageUrl)
const originalImage = await urlToImageElement(originalImageUrl)
const canvas = document.createElement('canvas')
if (canvas) {
canvas.width = originalImage.width
canvas.height = originalImage.height
const ctx = canvas.getContext('2d')
if (ctx) {
ctx.drawImage(maskImage, 0, 0, canvas.width, canvas.height)
const maskImagedata = ctx.getImageData(0, 0, canvas.width, canvas.height)
ctx.drawImage(originalImage, 0, 0, canvas.width, canvas.height)
const originalImagedata = ctx.getImageData(0, 0, canvas.width, canvas.height)
for (let i = 0; i < maskImagedata.data.length; i += 4) {
const alpha = (maskImagedata.data[i] + maskImagedata.data[i+1] + maskImagedata.data[i+2]) / 3
originalImagedata.data[i+3] = alpha;
}
ctx.putImageData(originalImagedata, 0, 0);
return canvas.toDataURL()
}
}
} catch (error) {
console.error(error)
}
}
Reference
이 문제에 관하여(캔버스로 초상화에 마스크를 적용하는 방법), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/arnosolo/how-to-apply-a-mask-into-a-portrait-with-canvas-2o5g텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)