5

我们可以在 HTML5 中通过 g.shadowBlur 方法绘制阴影,在大多数浏览器中都可以,除了 Chrome,当我绘制透明图像阴影时,如下所示,我该如何解决这个问题

我的 chrome 版本是“Chrome for Mac OS X,版本 27.0.1453.116”

在此处输入图像描述

<!DOCTYPE html>
<html>
<head>
    <title>Chrome HTML5 Canvas DrawImage Shadow Bug</title>
    <script type="text/javascript">
    function drawImage(evt){
        var image = evt.target;
        var w = image.width;
        var h = image.height;

        var canvas = document.getElementById('canvas');
        var g = canvas.getContext('2d');
        g.shadowColor = "#000000";
        g.shadowBlur = 10;
        g.shadowOffsetX = 0;
        g.shadowOffsetY = 0;
        g.drawImage(image, 20, 20);
        g.fillText("Text shadow in canvas", 10, 20)
    }
    </script>
</head>
<body>
<img src="http://www.google.com/images/icons/product/chrome-48.png" onload="drawImage(event)" style="-webkit-filter: drop-shadow(0px 0px 10px #222);" />
<div>
    <canvas id='canvas' style="background-color: #DDDDDD" />
</div>
</body>
</html>
4

1 回答 1

5

@Gustavo Carvalho 在对问题的评论中提到了将 img 绘制到 Chrom 上的解决方案。我认为它应该在这里用作答案,而不是评论,即在临时画布中绘制图像,然后用阴影绘制临时画布。这样,您将获得位图 img 阴影:

function drawImageWithShadow(img) {
  var ctx = document.getElementById('mainCanvas').getContext('2d');
  var tmpCanvas = document.createElement('canvas');
  var tmpCtx = tmpCanvas.getContext('2d');


  tmpCtx.drawImage(img, 0, 0);


  ctx.shadowOffsetX = 10;
  ctx.shadowOffsetY = 10;
  ctx.shadowColor = 'black';
  ctx.shadowBlur = 30;
  ctx.drawImage(tmpCanvas,0,0);
}
<img src="http://www.google.com/images/icons/product/chrome-48.png" onload="drawImageWithShadow(this)" />
<br>
<canvas id="mainCanvas" style="border:1px solid black"></canvas>

于 2015-08-23T19:23:54.697 回答