简体   繁体   中英

Canvas - Fill a shape created with multiple paths

What I want to do

I would like to draw a custom shape (for example a simple rectangle) which has different colors for each edge. I can do it with four paths, it works like a charm. BUT, in this way, it seems I can not fill the shape.

Trying the other way, I can draw the shape with one path and fill it, BUT in this case, I can not use different colors for the edges, because the last fillStyle will override the previous ones, even if I stroke the subpaths individually.

Is it possible to mix the two, by coloring subpaths individually, or by filling a shape consisting multiple paths?

在画布上使用不同的“图层”,一层用于填充颜色形状,另一层用于您拥有的每种颜色路径,z-index在画布上不起作用,只需确保首先绘制下面的内容,然后将所有内容包装在组<g>标记上,以使其更易于操作

After some experiment, I managed to solve my problem. It is not an ideal solution, because it has some overhead, but it works fine.

In the beginning of the drawing operation, I store the target coordinates in an array, and draw the whole stuff again and again. Each run is a new path. With .globalCompositeOperation = "destination-over" I can draw the lines under the existing ones, so each line can have a different color.

At the end of the drawing operation, the array contains all the coordinates of the shape, so the .fill() method can fill the path.

I hope it can help others:

 // get the canvas context var ctx = document.getElementById("myCanvas").getContext("2d"); // init shape array var shape = []; shape.push({ x: 0, y: 0 }); // or any other starting point // let's try draw(20, 20); draw(40, 40); draw(60, 60); // this is how we draw function draw(x, y) { // this is important // see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation ctx.globalCompositeOperation = "destination-over"; // this is just to be more visible ctx.lineWidth = 10; // get a random color ctx.strokeStyle = myRandomColor(); // save target coordinates shape.push({ x: x, y: y }); // reset the path ctx.beginPath(); // jump to the start point ctx.moveTo(shape[0].x, shape[0].y); // draw the whole stuff for (var i = 0; i < shape.length; i++) { ctx.lineTo(shape[i].x, shape[i].y); } ctx.stroke(); } function myRandomColor() { var colors = ["red", "green", "blue", "yellow", "pink"]; var rand = Math.round(Math.random() * 5); return colors[rand]; } 
 <canvas id="myCanvas"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM