0

I've draw a Japanese flag like shown below and I used toDataURL twice. The first one work fine same as the canvas but the second one appeared with black background and I don't know why??!

        canvas = document.getElementById('mycanvas')
        context = canvas.getContext('2d')
        context.fillStyle= 'red'
        canvas.style.border = '1px solid black'

        context.beginPath()
        context.moveTo(160 , 120)
        context.arc(160 , 120 , 70 , 0 , Math.PI *2 , false)
        context.closePath()
        context.fill()

        image = document.getElementById('myimage')
        image.style.border = '1px solid black'
        image.src = canvas.toDataURL()

        image2 = document.getElementById('myimage2')
        image2.style.border = '1px solid black'
        image2.src = canvas.toDataURL('image/jpeg' , 10)

and this is the result "I used Chrome and FireFox to test this" The result

markE
  • 102,905
  • 11
  • 164
  • 176
  • 1
    this is because by default, transparent pixels on canvas are set to `rgba(0,0,0,0)` so when you remove the alpha, by calling the `toDataURL('image/jpeg')`, these pixels are transformed to `rgb(0,0,0)`, which is black. To avoid it, draw a white rectangle as the background of your image. – Kaiido Mar 04 '16 at 09:45
  • Possible duplicate of [canvas.toDataURL results in solid black image?](http://stackoverflow.com/questions/26742180/canvas-todataurl-results-in-solid-black-image) – Kaiido Mar 04 '16 at 09:49
  • no i tried to use toDataURL just once and it also appear in black – Abdullah Alshaibany Mar 04 '16 at 10:00
  • Check out @Kaiido's comment ... it answers your question. – markE Mar 04 '16 at 17:47

0 Answers0