Reputation: 1791
I'm currently using Canvas to draw some curved lines
I know how to draw colored lines, but I don't find a way to render them with only a colored border..
For example :
const canvas = document.getElementsByTagName('canvas')[0],
ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(100, 10, 150, 75);
ctx.quadraticCurveTo(200, 140, 300, 100);
// this draws a 20px thick red line
ctx.lineCap = 'round';
ctx.lineWidth = 20;
ctx.strokeStyle = '#f00';
ctx.stroke();
<canvas width="350" height="150" style="border: 1px #303030 solid"></canvas>
I tried with clip()
, but it's not built to cut a line...
Is there a way to draw a real border around a thick line, to avoid filling it ?
I don't want to re-draw a thinner colored line over it, because I'm using a transparent canvas within a parent DOM element filled with an image (and don't want to move this background into the canvas)
Upvotes: 0
Views: 158
Reputation: 1791
I found a not perfect solution in a another post, using globalCompositeOperation
const canvas = document.getElementsByTagName('canvas')[0],
ctx = canvas.getContext('2d'),
borderWidth = 1;
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(100, 10, 150, 75);
ctx.quadraticCurveTo(200, 140, 300, 100);
// this draws a 20px thick red line
ctx.lineCap = 'round';
ctx.lineWidth = 20;
ctx.strokeStyle = '#f00';
ctx.stroke();
// just add this
ctx.globalCompositeOperation = "destination-out";
ctx.lineWidth = 20 - borderWidth * 2;
ctx.stroke();
ctx.globalCompositeOperation = "source-over";
<canvas width="350" height="150" style="border: 1px #303030 solid"></canvas>
In my case, it cut a double-hole into the canvas ; and it doesn't work if you have another background into the canvas...
Upvotes: 1
Reputation: 416
You can do this too!
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.quadraticCurveTo(100, 10, 150, 75);
ctx.quadraticCurveTo(200, 140, 275, 100);
ctx.quadraticCurveTo(285, 110,275, 120);
ctx.quadraticCurveTo(200, 160, 150, 95);
ctx.quadraticCurveTo(100, 30, 20, 40);
ctx.quadraticCurveTo(10, 30, 20, 20);
ctx.lineWidth = 2;
//ctx.fillStyle = '#f00';
ctx.stroke();
//ctx.fill();
</script>
</body>
</html>
Upvotes: 0