Inset-shadow on HTML5 canvas image

后端 未结 5 1886
遥遥无期
遥遥无期 2021-01-03 15:19

I\'ve seen this question before but the answers given are for canvas images that have been drawn on via path however, i\'m drawing an image.

Is it possible to creat

5条回答
  •  一整个雨季
    2021-01-03 15:48

    const width = 100 * devicePixelRatio;
    const height = 100 * devicePixelRatio;
    
    // original canvas
    const c = document.getElementById('canvas');
    c.width = 300 * devicePixelRatio;
    c.height = 300 * devicePixelRatio;
    c.style.width = '300px';
    c.style.height = '300px';
    const cctx = c.getContext('2d');
    cctx.fillStyle = 'rgb(20,205,75)';
    cctx.arc(150 * devicePixelRatio, 150 * devicePixelRatio, 50 * devicePixelRatio, 0, Math.PI * 2);
    cctx.fill();
    
    // temporary canvas
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    canvas.style.width = `${width / devicePixelRatio}px`;
    canvas.style.height = `${height / devicePixelRatio}px`;
    document.body.appendChild(canvas);
    var ctx = canvas.getContext('2d');
    
    // original object on temporary canvas
    ctx.arc(50 * devicePixelRatio, 50 * devicePixelRatio, 50 * devicePixelRatio, 0, Math.PI * 2);
    ctx.fill();
    
    // shadow cutting
    ctx.globalCompositeOperation = 'xor';
    ctx.arc(50 * devicePixelRatio, 50 * devicePixelRatio, 50 * devicePixelRatio, 0, Math.PI * 2);
    ctx.fill();
    
    // shadow props
    ctx.shadowBlur = 50;
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = -25;
    ctx.shadowColor = '#000';
    ctx.arc(50 * devicePixelRatio, 50 * devicePixelRatio, 50 * devicePixelRatio, 0, Math.PI * 2);
    ctx.fill();
    
    // shadow color
    ctx.globalCompositeOperation = 'source-in';
    ctx.fillStyle = 'blue';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // object cutting
    ctx.globalCompositeOperation = 'destination-in';
    ctx.arc(50 * devicePixelRatio, 50 * devicePixelRatio, 50 * devicePixelRatio, 0, Math.PI * 2);
    ctx.fill();
    
    // shadow opacity
    cctx.globalAlpha = .4
    
    // inserting shadow into original canvas
    cctx.drawImage(canvas, 200, 200);
    

    Colored shadow /w opacity

提交回复
热议问题