Total canvas memory use exceeds the maximum limit (Safari 12)

后端 未结 8 1665
栀梦
栀梦 2020-12-05 10:21

We are working on a visualization web application which use d3-force to draw a network on a canvas.

But now we’ve got a problem with browsers on iOS, where the proces

8条回答
  •  死守一世寂寞
    2020-12-05 10:32

    Someone posted an answer, that showed a workaround for this. The idea is to set height and width to 0 before deleting the canvases. It is not really a proper solution, but it will work in my cache system.

    I add a small example that creates canvases until an exception is thrown, then empties the cache and continues.

    Thank to the now anonymous person who posted this answer.

    let counter = 0
    
    // create a 1MB image
    const createImage = () => {
        const size = 512
    
        const canvas = document.createElement('canvas')
        canvas.height = size
        canvas.width = size
    
        const ctx = canvas.getContext('2d')
        ctx.strokeRect(0, 0, size, size)
        return canvas
    }
    
    const createImages = nbImage => {
        // create i * 1MB images
        const canvases = []
    
        for (let i = 0; i < nbImage; i++) {
            canvases.push(createImage())
        }
    
        console.log(`done for ${canvases.length} MB`)
        return canvases
    }
    
    const deleteCanvases = canvases => {
        canvases.forEach((canvas, i, a) => {
            canvas.height = 0
            canvas.width = 0
        })
    }
    
    let canvases = []
    const process = (frequency, size) => {
        setInterval(() => {
            try {
                canvases.push(...createImages(size))
                counter += size
                console.log(`total ${counter}`)
            }
            catch (e) {
                deleteCanvases(canvases)
                canvases = []
            }
        }, frequency)
    }
    
    
    process(2000, 1000)
    

提交回复
热议问题