Skip to content

Instantly share code, notes, and snippets.

@Reine0017
Last active Dec 15, 2020
Embed
What would you like to do?
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