Reputation: 1334
I am developing an application with HTML5 Canvas that displays a collection of shapes. On each shape I want one of the shape sides to have a stroke, but cannot do this without giving all sides a stroke or by using seperate lines and breaking the shape, stopping it from having a fill.
How would i draw a shape with a stroke on one side and a fill?
Thanks in advance.
Upvotes: 1
Views: 1298
Reputation: 35309
One way is to call stroke when you aren't fully done with the path, thus only stroking what you have already plotted out. Obviously though if you don't draw the side first you want stroked this wont work, so there's another option below.
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = canvas.height = 256;
ctx.fillStyle = "red";
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineTo(100,100);
ctx.stroke();
ctx.lineTo(100,200);
ctx.lineTo(50,100);
ctx.lineTo(50,50);
ctx.fill();
This is just a quick dirty proof of concept function as another way to achieve what you're looking for.
var shape = [{x:50,y:50}, {x:100, y:100}, {x:100, y:200}, {x:50,y:100}, {x:50, y:50}];
function drawShape(shape, strokeIndex){
ctx.beginPath();
ctx.moveTo(shape[0].x, shape[0].y);
for(var i = 1; i < shape.length; i++){
ctx.lineTo(shape[i].x, shape[i].y);
}
ctx.closePath();
ctx.fill();
// stroke
ctx.beginPath();
ctx.moveTo(shape[strokeIndex-1].x, shape[strokeIndex-1].y);
ctx.lineTo(shape[strokeIndex].x, shape[strokeIndex].y);
ctx.stroke();
}
drawShape(shape, 3);
Upvotes: 2