How to draw shadow image with HTML5 canvas in Chrome browser

We can draw the shadow using the g.shadowBlur method in HTML5, this is normal in most browsers except Chrome, when I draw a transparent shadow of the image, it looks like this, how can I solve this problem.

my chrome version is "Chrome for Mac OS X, version 27.0.1453.116"

enter image description here

<!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
source share
1 answer

The decision to bring img to work on Chrom was mentioned in a comment on a question from @Gustavo Carvalho. I thought it should be used here as an answer, not a comment, which is to draw an image in a temporary canvas and then draw a temporary area with a shadow. this way you get an img shadowed bitmap:

 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> 
+2
source

Source: https://habr.com/ru/post/1489692/


All Articles