Paint на canvas: рисование мышкой
Почему координаты нарисованных квадратиков не совпадают с координатами мышки?
var canvas = document.getElementById('cl');
var ctx = canvas.getContext('2d');
var myColor;
document.getElementById('color').oninput = function() {
myColor = this.value;
}
canvas.onmousedown = function(event) {
canvas.onmousemove = function(event) {
var x = event.offsetX;
var y = event.offsetY;
ctx.fillStyle = myColor;
ctx.fillRect(x - 0.5, y - 0.5, 10, 10);
ctx.fill();
}
canvas.onmouseup = function() {
canvas.onmousemove = null;
}
}
canvas {
width: 400px;
height: 400px;
border: 3px solid black;
margin: 40px;
}
<canvas id="cl">Подключите</canvas>
<input type="color" id="color">
Ответы (2 шт):
Изменения: <canvas id="cl" width='400' height='400'>Подключите</canvas>
Размер канваса (место, которое он занимает на странице) определяется стилями. В данном случае это canvas{width: 400px;height: 400px;border: 3px solid black; margin: 40px;}.
Но разряшение холста определяется отдельно, в его атребутах width и height, и может не совпадать с его размером. Тогда содержимое просто растягивается под размер, указанный в стилях. А дефолтное разрешение канвы: 300 * 150;
var canvas = document.getElementById('cl');
var ctx = canvas.getContext('2d');
var myColor;
document.getElementById('color').oninput = function(){
myColor=this.value;
}
canvas.onmousedown = function(event){
canvas.onmousemove = function(event){
var x = event.offsetX;
var y = event.offsetY;
ctx.fillStyle = myColor;
ctx.fillRect(x-0.5,y-0.5,10,10);
ctx.fill();
}
canvas.onmouseup = function(){
canvas.onmousemove = null;
}
}
canvas{width: 400px;height: 400px;border: 3px solid black; margin: 40px;}
<html>
<head>
<meta charset="utf-8"/>
<title>Сайт 2</title>
</head>
<body>
<noscript>Подключите JS</noscript>
<canvas width="400" height="400" id="cl">Подключите</canvas>
<input type="color" id="color">
</body>
<html>
Проблема в аппаратном масштабировании. Стили растягивают элемент, а в свойстве тега ты задаешь ему определенный размер.
Можно использовать атрибуты для тега (width, height), или же используй cl.width
Наглядно ты можешь это увидеть, посмотрев контекст элемента canvas:
