Flags with Repeats

From ProgZoo
Revision as of 08:42, 10 August 2021 by Andr3w (talk | contribs)
Jump to navigation Jump to search
<div style='background:silver;padding:5px'>
<canvas id='usr' width=--snippet-w-- height=--snippet-h--></canvas>
<canvas id='ans' width=--snippet-w-- height=--snippet-h-- style='display:none'></canvas>
</div>
--snippet-usr--
drawFlag(document.getElementById('usr').getContext('2d'));
(()=>{
  --snippet-ans--
  drawFlag(document.getElementById('ans').getContext('2d'));
})();
let [a,b] = ['usr','ans']
    .map(id=>document.getElementById(id))
    .map(elem=>elem.getContext('2d').getImageData(0,0,elem.width,elem.height))
let diff = a.data.map((v,i) => v===b.data[i]?1:0).reduce((acc,v)=>acc+v,0)*100/a.data.length;
let fb = document.createElement('div');
fb.innerText = `Score: ${diff.toFixed(1)}`;
document.body.appendChild(fb);
fetch(`/reportProgress.php?uid=--snippet-uid--&qid=--snippet-qid--&score=${diff}`);

In these exercises you can use a function star which draws a five pointed star on the canvas.

You can control the position of the star by calling the transform method of ctx.

Vietnam

The flag of Vietnam has a yellow five pointed star on a red background. This star is a popular device on many flags, we define the star once and use it many times in later flags.

The given star has a radius of 50, it is centred on 0,0 which is the wrong place. We must translate to put it in the right place. We can use the translate method to move the star to the right location.

The translate call is to the wrong location (50,50) - it should be at (100,75).

Flagvietnam.png

function drawFlag(ctx)
{
  ctx.fillStyle = 'red';
  ctx.translate(50,50);
  star(ctx);
}

function star(ctx)
{
  ctx.beginPath();
  [ [ 0,-50],[11,-16],[48,-16],[18,6],[30,41],
    [ 0,18],[-30,41],[-18,6],[-48,-16],[-11,-16]
  ].forEach((xy) => ctx.lineTo(xy[0],xy[1]));
  ctx.fill();
}
function drawFlag(ctx)
{
  ctx.fillStyle = 'red';
  ctx.fillRect(0,0,200,150);
  ctx.translate(100,75);
  ctx.fillStyle='yellow';
  star(ctx);
}

function star(ctx)
{
  ctx.beginPath();
  [ [ 0,-50],[11,-16],[48,-16],[18,6],[30,41],
    [ 0,18],[-30,41],[-18,6],[-48,-16],[-11,-16]
  ].forEach((xy) => ctx.lineTo(xy[0],xy[1]));
  ctx.fill();
}