1

I have 2 half circles which are one is red and other is green. I want to combine them, how can I do that? I am adding my canvas codes:

const canvas_ok = new OffscreenCanvas(16, 16)
const context_ok = canvas_ok.getContext('2d')
context_ok.arc(8, 8, 8, 0, Math.PI, true)
context_ok.fillStyle = '#56BB08'
context_ok.fill()
const img_ok = context_ok.getImageData(0, 0, 16, 8)
const canvas_err = new OffscreenCanvas(16, 16)
const context_err = canvas_err.getContext('2d')
context_err.arc(8, 8, 8, 0, Math.PI)
context_err.fillStyle = '#FF0000'
context_err.fill()
const img_err = context_err.getImageData(0, 0, 16, 8)
Kaiido
  • 123,334
  • 13
  • 219
  • 285
Ceren Keklik
  • 291
  • 2
  • 11
  • What exactly do you mean by "combine them"? Are you trying to draw both on the same canvas? Or position them in a specific way? – DBS Nov 25 '21 at 09:57
  • @DBS I want a circle that upper half is green and bottom half is red – Ceren Keklik Nov 25 '21 at 10:00

1 Answers1

1

To get a single image with both halves, the easiest approach is to use a single canvas, and draw both arcs on that canvas like this:

// Create the single canvas and context
const canvas = new OffscreenCanvas(16, 16)
const context = canvas.getContext('2d')

// Green half
context.beginPath()
context.arc(8, 8, 8, 0, Math.PI, true)
context.closePath()
context.fillStyle = '#56BB08'
context.fill()

// Red half
context.beginPath()
context.arc(8, 8, 8, 0, Math.PI, false)
context.closePath()
context.fillStyle = '#FF0000'
context.fill()


// This is just adding the resulting image to the document so the example is visible
canvas
  .convertToBlob()
  .then(blob => {
    var reader = new FileReader()
    reader.onload = (e) => {
      document.write(`<img src="${e.target.result}" />`)
    }
    reader.readAsDataURL(blob)
  })
DBS
  • 9,110
  • 4
  • 35
  • 53