I am seeing slow canvas drawing the first time I use another canvas as the drawing source. Subsequent canvas to canvas .drawImage calls are fine until I swap images (and then I see the same issue again).
Sample code below - an image is loaded and then 4 canvases are created, the 1st canvas is draw from the image itself, the 2nd canvas is drawn from the 1st, etc. After the canvases are created the source image is swapped and the code run again.
var sourceImage = new Image(); // Original image
var myImages = []; // Array of image and canvases references
myImages[0] = sourceImage; // Set first myImage to image source
// Image onload
sourceImage.onload = function () {
console.log("Imageload", new Date() - t0);
myImages[0] = sourceImage;
// Loop to create and draw on canvases
for (var i = 1; i <= 4; i += 1) {
// Create canvas
myImages[i] = document.createElement("canvas");
// Set canvas dimensions to same as original image
myImages[i].width = myImages[0].width;
myImages[i].height = myImages[0].height;
// Draw last canvas / image onto this canvas
t0 = new Date();
myImages[i].getContext("2d").drawImage(
myImages[i - 1],
0,
0,
myImages[i].width,
myImages[i].height
);
console.log("drawImage", i, new Date() - t0);
}
// Finished with black.jpg so load white.jpg
if (sourceImage.getAttribute("src") == "images/black.jpg") {
sourceImage.src = "images/white.jpg"
}
}
// Load image
t0 = new Date();
sourceImage.src = "images/black.jpg"
The console output is ...
Imageload 36
drawImage 1 0
drawImage 2 255
drawImage 3 0
drawImage 4 0
Imageload 35
drawImage 1 0
drawImage 2 388
drawImage 3 1
drawImage 4 1
My question is why is the 2nd canvas drawing slow? I have tried various image files, and different canvas sizes but always see the same outcome. I have tested on Chrome and Safari.
If the slow draw was on the first canvas I could accept that although the .onload fired there was still something going on with the image. But the slowness is on the second canvas i.e. the first has been drawn from the image without issue.