gpt4 book ai didi

javascript - 在 HTML5 Canvas 上填充非矩形

转载 作者:行者123 更新时间:2023-12-03 02:44:45 24 4
gpt4 key购买 nike

我在 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>

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

最佳答案

尝试关闭每一侧的路径,然后调用填充:

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>

关于javascript - 在 HTML5 Canvas 上填充非矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48143340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com