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>
Resizing the canvas with CSS stretches its contents, similar to how an <img>
behaves.
Stretching offsets the canvas coordinates relative to your mouse click.
For example, a click at coordinates (5,5) could translate to stretched canvas coordinates of (15,25).
Sizing the canvas
The displayed size of the canvas can be changed using a stylesheet. The image is scaled during rendering to fit the styled size. If your renderings seem distorted, try specifying your width and height attributes explicitly in the attributes, and not using CSS.
You can set canvas dimensions via JavaScript in order to make it fill the viewport.
var image = document.getElementById("image");
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = window.innerWidth;
c.height = window.innerHeight;
function onCanvasClick() {
var xLoc = event.clientX;
var yLoc = event.clientY;
ctx.drawImage(image, xLoc, yLoc);
}
body {
margin: 0;
}
#myCanvas {
display: block;
background-color: rgba(58, 154, 221, 0.3);
}
#image {
display: none;
}
<canvas id="myCanvas" onmousedown="onCanvasClick()" width="100%" height="100%">You dont support this!</canvas>
<img id="image" src="//via.placeholder.com/50">
For more reference, see:
HTML5 Canvas distorted?
Resize HTML5 canvas to fit window
HTML5 Canvas 100% Width Height of Viewport?
Resizing will clear the canvas, so a responsive design will require additional functionality.
Matthew Crumley has ideas for redrawing/scaling existing content when resizing.