Created
November 1, 2017 14:39
-
-
Save ear1grey/88ca0b500ce114a0d4bdddde9ff7d6db to your computer and use it in GitHub Desktop.
Example of using context.scale in HTML5 canvas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let can = document.createElement('canvas'); | |
let c = can.getContext("2d"); | |
document.body.appendChild(can); | |
can.width = 300; | |
can.height = 500; | |
can.style = "border: dashed black thin;"; | |
// Calculate scale value so that using dimensions | |
// between 0 and 100 on either axis resultsin a | |
// draing that fills the canvas without overflowing | |
// or stretching. | |
let scale = Math.min(can.width, can.height) / 100; | |
// draw the shape first with the default scaling | |
// then apply the scale value and redraw in a different colour | |
drawStuff(c, "red"); | |
c.scale(scale, scale); | |
drawStuff(c, "blue"); | |
function drawStuff(c, color) { | |
c.strokeStyle = color; | |
// draw a 100x100 box | |
c.beginPath(); | |
c.moveTo(0,0); | |
c.lineTo(100,0); | |
c.lineTo(100,100); | |
c.lineTo(0,100); | |
c.closePath(); | |
c.stroke(); | |
// draw a 40x40 bow in the | |
// middle of the 100x100 box | |
c.beginPath(); | |
c.moveTo(30,30); | |
c.lineTo(70,70); | |
c.lineTo(70,30); | |
c.lineTo(30,70); | |
c.closePath(); | |
c.stroke(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment