Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The correct answer is, of course, Vincent's one.<br> I fumbled a bit with this rotation/translation thing, and I think my little experiments could be interesting to show:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;test&lt;/title&gt; &lt;script type="text/javascript"&gt; canvasW = canvasH = 800; imgW = imgH = 128; function startup() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // Just to see what I do... ctx.strokeRect(0, 0, canvasW, canvasH); var img = new Image(); img.src = 'player.png'; img.onload = function() { // Just for reference ctx.drawImage(img, 0, 0, 128, 128); ctx.drawImage(img, canvasW/2 - imgW/2, canvasH/2 - imgH/2, 128, 128); mark(ctx, "red"); // Keep current context (transformations) ctx.save(); // Put bottom center at origin ctx.translate(imgW/2, imgH); // Rotate // Beware the next translations/positions are done along the rotated axis ctx.rotate(45 * Math.PI / 180); // Mark new origin mark(ctx, "red"); // Restore position ctx.translate(-imgW/2, -imgH); ctx.drawImage(img, 0, 0, imgW, imgH); mark(ctx, "green"); // Draw it an wanted position ctx.drawImage(img, canvasW/2, canvasH/3, imgW, imgH); // Move elsewhere: ctx.translate(canvasW/2, canvasH/2); ctx.drawImage(img, 0, 0, imgW, imgH); mark(ctx, "blue"); ctx.restore(); } } function mark(ctx, color) { ctx.save(); //~ ctx.fillStyle = color; //~ ctx.fillRect(-2, -2, 4, 4); ctx.strokeStyle = color; ctx.strokeRect(0, 0, imgW, imgH); ctx.restore(); } &lt;/script&gt; &lt;/head&gt; &lt;body onload='startup();'&gt; &lt;canvas id="canvas" style="position: absolute; left: 300px; top: 300px;" width="800" height="800"&gt;&lt;/canvas&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>My stumbling issue was that positioning the rotated figure is hard, because it is along the rotated axis: either we have to do some trigo math to paint at the primitive origin, or we have to draw on a secondary hidden canvas and then paint it on the target one.<br> Unless somebody else has a better idea?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload