2
\$\begingroup\$

I have the following code, which draws a overlay image onto video for each frame:

video.addEventListener( 'play', function() {

    var $this = this; // cache

    (function drawCurrentFrameToCanvas() {
        if ( ! $this.paused && ! $this.ended ) {
            drawImage();
            requestAnimationFrame( drawCurrentFrameToCanvas ); // rAF is supported by most browsers in nowdays.
        }
    })();

}, 0);

function drawImage() {

    var points = getTrackingPoints();

    if( ! points ) return;  

    var lh = points.pt4.y - points.pt2.y; 
    var lw = points.pt2.x - points.pt1.x; 
    var pw = ( lw < points.pt4.x - points.pt3.x ) ? points.pt4.x - points.pt3.x : lw; /* get longest left/right side */
    var ph = ( lh < points.pt3.y - points.pt1.y ) ? points.pt3.y - points.pt1.y : lh; /* get longest top/bottom side */
    var dx = points.pt2.x - points.pt1.x;
    var dy = points.pt2.y - points.pt1.y;
    var radianAngle = (Math.atan2(dy,dx)+Math.PI*2) % (Math.PI*2);

    ctx.clearRect( 0 , 0 , canvas.width, canvas.height ); 

    dot( points.pt1.x, points.pt1.y );
    dot( points.pt2.x, points.pt2.y );
    dot( points.pt3.x, points.pt3.y );
    dot( points.pt4.x, points.pt4.y );

    ctx.save();

    ctx.translate( points.pt1.x, points.pt1.y );
    ctx.rotate( radianAngle );
    ctx.translate( -points.pt1.x, -points.pt1.y );

    // ctx.globalAlpha = 0.5;

    if( typeof template !== 'undefined' ) {
        ctx.drawImage(template, points.pt1.x, points.pt1.y, pw, ph);
    }

    ctx.restore();

}

Where template used here is standard HTMLImageElement:

ctx.drawImage(template, points.pt1.x, points.pt1.y, pw, ph); 

Is there a way to optimize it, to work faster?

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.