JavaScript event for canvas resize

前端 未结 5 1294
礼貌的吻别
礼貌的吻别 2020-12-16 12:17

It appears that altering the dimensions of a canvas clears any drawing already done on that canvas.

Is there an event that fires on canvas resize, so I can hook it a

5条回答
  •  北海茫月
    2020-12-16 12:38

    I didn't find any build-in events to detect new canvas dimensions, so I tried to find a workaround for two scenarios.

    function onresize()
    {
        // handle canvas resize event here
    }
    
    var _savedWidth = canvas.clientWidth;
    var _savedHeight = canvas.clientHeight;
    function isResized()
    {
        if(_savedWidth != canvas.clientWidth || _savedHeight != canvas.clientHeight)
        {
            _savedWidth = canvas.clientWidth;
            _savedHeight = canvas.clientHeight;
            onresize();
        }
    }
    
    window.addEventListener("resize", isResized);
    
    (new MutationObserver(function(mutations)
    {
        if(mutations.length > 0) { isResized(); }
    })).observe(canvas, { attributes : true, attributeFilter : ['style'] });
    
    1. For detecting any JavaScript canvas.style changes, the MutationObserver API is good for. It doesn't detect a specific style property, but in this case it is sufficient to check if canvas.clientWidth and canvas.clientHeight has changed.

    2. If the canvas size is declared in a style-tag with a percent unit, we have a problem to interpret the css selectors correctly (>, *, ::before, ...) by using JavaScript. I think in this case the best way is to set a window.resize handler and also check the canvas client size.

提交回复
热议问题