Skip to content

Instantly share code, notes, and snippets.

@Reine0017
Last active July 13, 2022 04:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Reine0017/52349a63eb3234e316a1ac4a5d1cead2 to your computer and use it in GitHub Desktop.
Save Reine0017/52349a63eb3234e316a1ac4a5d1cead2 to your computer and use it in GitHub Desktop.
Simple Drawing app - sketch.js (1)
window.addEventListener("load", () => {
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = "assets/images/reinePic.jpg";
img.onload = () => {
const [img_scaled_width, img_scaled_height] = drawImageToScale(img, ctx);
canvas.width = img_scaled_width;
canvas.height = img_scaled_height;
window.addEventListener('resize', drawImageToScale(img,ctx));
}
// variables
let painting = false;
function startPosition(e){
painting = true;
draw(e);
}
function finishedPosition(){
painting = false;
ctx.beginPath();
}
function draw(e){
if (!painting)
return;
ctx.lineWidth = 3;
ctx.lineCap = 'round';
//console.log(e.clientX, e.clientY);
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX, e.clientY);
}
// eventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishedPosition);
canvas.addEventListener("mousemove", draw)
});
function drawImageToScale(img, ctx){
const img_width = 650;
const scaleFactor = img_width / img.width;
const img_height = img.height * scaleFactor;
ctx.drawImage(img, 0, 0,img_width,img_height);
return [img_width,img_height];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment