How to draw a blurry circle on HTML5 canvas?

十年热恋 提交于 2019-11-27 07:05:42

I'd strongly suggest against blur algorithms unless you are blurring some already-existing drawing that is complex.

For your case, just draw a rect with a radial gradient.

  var radgrad = ctx.createRadialGradient(60,60,0,60,60,60);
  radgrad.addColorStop(0, 'rgba(255,0,0,1)');
  radgrad.addColorStop(0.8, 'rgba(228,0,0,.9)');
  radgrad.addColorStop(1, 'rgba(228,0,0,0)');

  // draw shape
  ctx.fillStyle = radgrad;
  ctx.fillRect(0,0,150,150);

Example:

http://jsfiddle.net/r8Kqy/48/

You probably can obtain the bitmap pixel array and apply some blurring algorithm on top of it. For example: http://www.jhlabs.com/ip/blurring.html

You may find the context.filter property useful

var canvas = document.getElementById('canvas');

var context = canvas.getContext('2d');

context.filter = "blur(16px)";

context.fillStyle = "#f00";
context.beginPath();
context.arc(100, 100, 50, 0, Math.PI * 2, true);
context.fill();
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>

<body>
  <canvas width=200 height=200 id='canvas'></canvas>
</body>

</html>

Note as of April 2017, IE, Opera and Safari don't support this

You can draw a blurred circle with the following function:

function drawblurrycircle(context, x, y, radius, blur)
{
     context.shadowBlur = blur;
     context.shadowOffsetX = 0;
     context.shadowOffsetY = 0;

     context.fillStyle="#FF0000";
     context.shadowColor="#FF0000"; //set the shadow colour to that of the fill

     context.beginPath();
     context.arc(x,y,radius,0,Math.PI*2,true);
     context.fill();
     context.stroke();
}

If you are still interested in seeing this effect done with EaselJS, this might help JSFiddle EaselJS blur

var stage = new createjs.Stage("test");
var s = new createjs.Shape();
var g = s.graphics;
g.f("#FF0000").dc(0, 0, 75);
s.x = 100;
s.y = 100;
s.filters = [new createjs.BoxBlurFilter(5, 5, 3)];
stage.addChild(s);
s.cache(-100, -100, 200, 200);
s.alpha = 0.5;
stage.update();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!