<canvas id="canvas1" width="50" height="50"></canvas>
<br>
<canvas id="canvas2" width="500" height="500"></canvas>
<canvas id="canvas3" width="500" height="500"></canvas>
var canvas1 = document.getElementById("canvas1")
var ctx1 = canvas1.getContext("2d");
var canvas2 = document.getElementById("canvas2")
var ctx2 = canvas2.getContext("2d");
var canvas3 = document.getElementById("canvas3")
var ctx3 = canvas3.getContext("2d");
ctx1.fillStyle = "rgb(10,80,80)";
ctx1.fillRect(0,0,50,50);
ctx1.fillStyle = "rgb(80,180,180)";
ctx1.fillRect(4,4,42,42);
ctx3.scale(10, 10);
ctx2.drawImage(canvas1, 0, 0, 50, 50, 0, 0, 500, 500);
ctx3.drawImage(canvas1, 0, 0, 50, 50);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
drawImage scaling | |
context scaling |
Test name | Executions per second |
---|---|
drawImage scaling | 574421.9 Ops/sec |
context scaling | 364179.1 Ops/sec |
Let's dive into the Benchmark Definition and test cases.
Benchmark Definition
The benchmark measures two different approaches to draw an image on a canvas: drawImage
with scaling and context scaling (also known as "stretching" or "resizing").
The Script Preparation Code
section of the benchmark setup creates three canvases (canvas1
, canvas2
, and canvas3
) using JavaScript's 2D drawing API. The third canvas is scaled by a factor of 10x10 using the scale()
method.
Options being compared
Two options are being compared:
drawImage
with scaling: This approach uses the drawImage()
method to draw an image on a new canvas, specifying the x and y coordinates, width, height, and source rectangle (which is used to scale the image).scale()
method): This approach uses the scale()
method to directly modify the canvas's transformation matrix, which allows for scaling without needing to draw an intermediate image.Pros and Cons
Here are some pros and cons of each approach:
drawImage
with scaling:drawImage()
method.scale()
method):drawImage
approach.Library usage
In this benchmark, no specific JavaScript library is used beyond the standard 2D drawing API (Canvas API). However, some modern browsers may use optimized implementations of these APIs that rely on underlying libraries or frameworks.
Special JS features/syntax
This benchmark does not appear to utilize any special JavaScript features or syntax, such as async/await, promises, or ES6+ features like template literals or arrow functions.
Alternative approaches
Other alternatives for drawing images on canvases include:
getImageData()
and putImageData()
methods.drawImage()
method to draw individual frames.These alternative approaches can offer different trade-offs in terms of performance, complexity, and flexibility compared to the drawImage
with scaling and context scaling methods used in this benchmark.