If I single-step the following js code (using Firefox 44 on OS X), I get the desired result: the context.setTransform(...)
is executed and the image is magnified by 2.
If on the other hand I run the code in FF by simply loading the page, it is as if the transformation is never applied. (The outcome is then identical to having commented out the context.setTransform(...)
line.)
The culprit appears to be the context.save()
/context.restore()
pair. Commenting these two lines out produces the desired outcome directly. But it is good practice to wrap graphics code with save/restore to isolate the context, especially the current transformation.
You can generate the image on your side with convert -size 100x100 plasma:fractal plasma_fractal1.jpg
.
I understand that the order of setting img.src is rather finicky, but I'm heeding the correct, multi-browser-safe, order.
What is going on?
myfrac.html
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
div {
width: 600px;
height: 400px;
background: #BBBBBB;
margin: 20px;
padding: 15px;
}
#myCanvas {
background-color: white;
border: 2px solid black;
width: 400px;
height: 300px;
}
</style>
</head>
<body>
<div>
<canvas id="myCanvas">
<p>Canvas not available</p>
</canvas>
</div>
<script src="myfrac.js" type="text/javascript"></script>
<script>myDrawingFunction()</script>
</body>
</html>
myfrac.js
function myDrawImage(context, imageURI, x, y, w, h)
{
var img = new Image;
img.onload = function(){
context.drawImage(img, x, y, w, h);
};
img.src = imageURI;
}
function myDrawingFunction()
{
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.setTransform(2, 0, 0, 2, 0, 0);
myDrawImage(context, "plasma_fractal1.jpg", 0, 0, 200, 200);
context.restore();
}