Search code examples
html5-canvasoffscreen-canvas

OFFSCREEN-CANVAS: How can I combine 2 different half circles that are in different canvas?


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)

Solution

  • 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)
      })