Search code examples
canvashtml2canvas

Take a part of canvas and draw it as image on another canvas at every move


I had a canvas and set mouse move event on it , I need to draw a part of canvas where user move on another canvas .

public drawImage(pointerPoint: { x: number, y: number }, panelCanvas: JQuery): void {
    let canvasImage = new Image(),
        context = this.context();

    canvasImage.onload = () => {
        context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
        context.drawImage(canvasImage, pointerPoint.x - 50, pointerPoint.y - 50, CANVAS_WIDTH, CANVAS_HEIGHT, 0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    };
    canvasImage.src = (<HTMLCanvasElement>(panelCanvas[0])).toDataURL();
}

but the problem is this method call frequently , It will get data url for a many canvas and then it wait for onload , This causes canvas slowness is there any way to do that faster ?


Solution

  • drawImage will draw image like elements. The canvas is image like thus there is no need to convert to data url just draw one canvas onto the other.. EG

    public drawImage(pointerPoint: { x: number, y: number }, panelCanvas: JQuery): void {
         const context = this.context();
         context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
         context.drawImage(
             panelCanvas[0], 
             pointerPoint.x - 50, pointerPoint.y - 50, CANVAS_WIDTH, CANVAS_HEIGHT, 
             0, 0, CANVAS_WIDTH, CANVAS_HEIGHT
         );
    
    }