简体   繁体   English

在HTML5画布上填充非矩形

[英]Filling in non-rectangles on HTML5 Canvas

I have a cube made from lines and rectangles on a canvas and I want to fill in areas that aren't rectangles. 我有一个由画布上的线条和矩形组成的立方体,我想填写不是矩形的区域。

Here is my code and jsFiddle . 这是我的代码和jsFiddle

 var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') var height = 250 var width = 250 var edge = { x: 8, y: 8 } canvas.height = height canvas.width = width ctx.beginPath() ctx.rect(50, 50, 100, 100) ctx.rect(100, 100, 100, 100) ctx.strokeStyle = 'black' ctx.stroke() ctx.beginPath() ctx.moveTo(50, 150) ctx.lineTo(100, 200) ctx.moveTo(50, 50) ctx.lineTo(100, 100) ctx.moveTo(150, 50) ctx.lineTo(200, 100) ctx.moveTo(150, 150) ctx.lineTo(200, 200) ctx.strokeStyle = 'gray' ctx.lineWidth = 2 ctx.stroke() 
 canvas { background: white; /*border-style:solid;*/ } 
 <canvas></canvas> 

How would I fill in these areas? 我将如何填写这些区域? 这些地区

Try to closepath for each side and then call fill: 尝试在每一侧都闭合路径,然后调用fill:

 var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') var height = 250 var width = 250 var edge = { x: 8, y: 8 } canvas.height = height canvas.width = width ctx.beginPath() ctx.rect(50, 50, 100, 100) ctx.rect(100, 100, 100, 100) ctx.strokeStyle = 'black' ctx.stroke() ctx.beginPath() ctx.moveTo(50, 150) ctx.lineTo(100, 200) ctx.lineTo(100, 100) ctx.lineTo(50, 50) ctx.lineTo(50, 150) //the path is closed now, the fill would color the area ctx.strokeStyle = 'blue' ctx.lineWidth = 2 ctx.stroke() ctx.fillStyle="red"; ctx.fill(); ctx.moveTo(50, 50) ctx.lineTo(100, 100) ctx.moveTo(150, 50) ctx.lineTo(200, 100) ctx.moveTo(150, 150) ctx.lineTo(200, 200) ctx.strokeStyle = 'blue' ctx.lineWidth = 2 ctx.stroke() 
 canvas { background: white; /*border-style:solid;*/ } 
 <canvas></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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