My <canvas>
element takes up 100vw
and 100vh
. I want to be able to click anywhere on it and have a picture drawn there. Right now, when I click on the screen, the image does not get drawn anywhere close to where I click. The closer I click to the top left corner, the closer it is. But if I deviate from the corner even slightly, the image gets pushed really far down and to the right.
How can I calculate the offset I seem to need in order to get the image to draw exactly where I click?
//var count1 = (Math.floor(Math.random() * screen.width)) + 1;
//var count2 = (Math.floor(Math.random() * screen.height)) + 1;
function onCanvasClick() {
var image = document.getElementById("image");
var xLoc = event.clientX;
var yLoc = event.clientY;
var loc = "xLoc is: " + xLoc + " | yLoc is: " + yLoc;
console.log(loc);
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(image, xLoc, yLoc);
}
#myCanvas {
width: 99vw;
height: 99vh;
border: 2px solid rgba(255, 255, 255, 0.5);
background-color: rgba(58, 154, 221, 0.3);
}
#image {
width: 100px;
height: 100px;
display: none;
}
<canvas id="myCanvas" onmousedown="onCanvasClick()">You dont support this!</canvas>
<img id="image" src="//via.placeholder.com/100"></img>