HTML5画布:用颜色填充透明图像并在顶部绘制
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTML5画布:用颜色填充透明图像并在顶部绘制相关的知识,希望对你有一定的参考价值。
我正在尝试在另一张充满颜色的图像上绘制透明图像。我有这样的代码结构,有一个基本图像,另一个透明image_1
乘以它,然后image_2
应该用颜色填充并绘制。使用fillStyle
和fillRect
无法使其正常工作。
image_1.src = 'image_1_url';
image_1.onload = () =>
context.globalCompositeOperation = 'multiply';
context.drawImage(image_1, 0, 0, canvas.width, canvas.height);
image_2.src = 'image_2_url';
image_2.onload = () =>
//fill image_2 with a color and draw it on top of canvas
我应该以哪种顺序使用颜色填充和globalCompositeOperations?
答案
简单的解决方案:使用第二个画布。
(async () =>
const [ cat, star, hex ] = await Promise.all( loadImages( [ "kNpEG.jpg", "PPfrd.png", "x1ykw.png" ], 'https://i.stack.imgur.com/' ) );
// the visible canvas
const canvas = document.getElementById( 'canvas' );
const ctx = canvas.getContext( '2d' );
// create an offcreen copy
const canvas2 = canvas.cloneNode();
const ctx2 = canvas2.getContext( '2d' );
// on the visible canvas
// we can apply simply the first step source-over operation
ctx.drawImage( cat, 0, 0 );
ctx.drawImage( star, 0, 0 );
// on the offsreen canvas we apply the color blending
ctx2.fillStyle = "red";
ctx2.fillRect( 0, 0, 200, 200 );
ctx2.globalCompositeOperation = "destination-in";
ctx2.drawImage( hex, 0, 0 );
// now we can draw it on the visible canvas, still as source-over
ctx.drawImage( canvas2, 0, 0 );
)().catch( console.error );
function loadImages( filenames, path = "" )
return filenames.map( filename => new Promise( (res, rej ) =>
const img = new Image();
img.onload = (evt) => res( img );
img.onerror = rej;
img.src = path + filename;
) );
<canvas id="canvas" width="200" height="200"></canvas>
以上是关于HTML5画布:用颜色填充透明图像并在顶部绘制的主要内容,如果未能解决你的问题,请参考以下文章