Max Francisco
Max Francisco

Reputation: 1

How to draw this in html5 canvas?

How do I draw this in html5 canvas? I can only do the rectangle with round corners part.

What I want to draw

 <canvas id="myCanvas" width="578" height="200"></canvas>
 <script type="text/javascript">
 function roundRect(x, y, w, h, radius)
 {
 var canvas = document.getElementById("myCanvas");
 var context = canvas.getContext("2d");
 var r = x + w;
 var b = y + h;
 context.beginPath();
 context.strokeStyle="green";
 context.lineWidth="4";
 context.moveTo(x+radius, y);
 context.lineTo(r-radius, y);
 context.quadraticCurveTo(r, y, r, y+radius);
 context.lineTo(r, y+h-radius);
 context.quadraticCurveTo(r, b, r-radius, b);
 context.lineTo(x+radius, b);
 context.quadraticCurveTo(x, b, x, b-radius);
 context.lineTo(x, y+radius);
 context.quadraticCurveTo(x, y, x+radius, y);
 context.stroke();
 }
 roundRect(10, 10, 200, 100, 20);
 </script>

Upvotes: 0

Views: 49

Answers (1)

enxaneta
enxaneta

Reputation: 33054

If you prefer rounded corners there is a easier way: you may use the context method arcTo()For example to draw a rectangle with rounded corners you can write:

 var canvas = document.getElementById("myCanvas");
 var ctx = canvas.getContext("2d");
 
 function roundRect(x, y, w, h, r){

 var x0 = x, y0 = y;
 var x1 = x0+w, y1 = y0;
 var x2 = x1, y2 = y0+h;
 var x3 = x, y3 = y2;
							
 ctx.strokeStyle = "green";
 ctx.lineWidth=4;
 ctx.beginPath();
 ctx.moveTo(x3,y3-r);
						
 ctx.arcTo(x0,y0,x1,y1,r);
 ctx.arcTo(x1,y1,x2,y2,r);
 ctx.arcTo(x2,y2,x3,y3,r);
 ctx.arcTo(x3,y3,x0,y0,r);
 ctx.stroke(); 
   }
		

roundRect(10, 10, 200, 100, 10);
<canvas id="myCanvas" width="578" height="200"></canvas>

However the image of the 2 rectangles may be done using 2 simple canvas rectangles and an SVG filter like this:

 var canvas = document.getElementById("c");
 var ctx = canvas.getContext("2d");
 ctx.fillStyle = "green";
 ctx.fillRect(10, 10, 100, 100)
 ctx.fillRect(100, 100, 30, 30)
canvas{filter: url(#goo);}
<svg width="1" height="1">
<defs>
<filter id="goo">
      <feGaussianBlur in="SourceGraphic" stdDeviation="4" result="blur" />
      <feColorMatrix in="blur" mode="matrix" 
                     values="1 0 0  0   0  
                             0 1 0  0   0  
                             0 0 1  0   0  
                             0 0 0 40 -28" result="goo" />
      
    </filter> 
  </defs>
</svg>
<canvas id="c" width="578" height="200"></canvas>

If you are not familiar with The Gooey Effect you may read this article: https://css-tricks.com/gooey-effect/

I hope this helps

Upvotes: 1

Related Questions