填写HTML5 Canvas上的非矩形

时间:2018-01-08 01:55:35

标签: javascript html5 canvas

我在画布上有一个由线条和矩形组成的立方体,我想要填充不是矩形的区域。

这是我的代码和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>
&#13;
&#13;
&#13;

我如何填写这些区域?these areas

1 个答案:

答案 0 :(得分:1)

尝试关闭每一边的路径,然后调用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>