为什么我在这个画布上创建的矩形不能放在正确的位置? [英] Why are the rectangles I am creating on this canvas not getting put in the right spot?
问题描述
我想创建一个简单的页面,您可以在其中单击并可以在画布上创建矩形。它将用户的鼠标点击作为输入,然后从点击的x和y创建一个矩形。但是,它把矩形放在边上一些数量,我不知道为什么。
I am trying to create a simple page where you click and can create rectangles on a canvas. It takes the user's mouse clicks as input, and then creates a rectangle from the x and y of the click. However, it places the rectangle off to the side by some amount, and I am not sure why.
小提琴:https://jsfiddle.net/2717s53h/
HTML
<canvas id="cnv"></canvas>
CSS
#cnv{
width:99vw;
height:98vh;
background-color:#faefbd;
}
JAVASCRIPT
$(function () {
var canvas = $('#cnv');
var canvObj = document.getElementById('cnv');
var ctx = canvObj.getContext('2d');
var point1 = {};
var point2 = {};
canvas.click(function (e) {
console.log(e);
var x = e.pageX;
var y = e.pageY;
console.log(x);
console.log(y);
if (Object.keys(point1).length == 0)
{
point1.x = x;
point1.y = y;
}
else if (Object.keys(point2).length == 0)
{
point2.x = x;
point2.y = y;
console.log(point1);
console.log(point2);
var width = point2.x - point1.x;
var height = point2.y - point1.y;
width = width < 0 ? width * -1 : width;
height = height < 0 ? height * -1 : height;
ctx.fillRect(x, y, 10, 10);
point1 = {};
point2 = {};
}
});
});
推荐答案
CSS高度/宽度和HTML canvas属性height和width:前者定义画布在页面中占用的空间;后者定义呈现表面。在concreto中,假设您有以下画布:
There is a difference between the CSS height/ width and the HTML canvas attributes height and width: the former defines the space the canvas occupies in the page; the latter defines the rendering surface. In concreto, suppose you have the following canvas:
<canvas height="400" width="600"></canvas>
使用尺寸为1200x800的视口,画布的CSS设置为 width:100%; height:100%;
,那么你的画布会被渲染为两倍于高度和宽度的大小和模糊(例如在你的小提琴中;比10px)。因此,页面坐标不与画布的坐标同步。
with a viewport of a 1200x800 size and the canvas' CSS is set to width: 100%; height: 100%;
, then your canvas will be rendered as stretched out twice as big and blurry in both height and width (like in your fiddle; clearly those rectangles are bigger than 10px). As a consequence, the page coordinates are not in sync with the canvas' coordinates.
根据规格,您的小提琴的画布呈现表面是300x150,因为您没有指定宽度/ height属性:
As per the specification, your fiddle's canvas rendering surface is 300x150 because you didn't specify the width/height attributes:
width属性默认值为300,height属性默认值为150.
The width attribute defaults to 300, and the height attribute defaults to 150.
查看您的小提琴的略微更正版本。
因此,我的建议(作为HTML画布上的非专家)会总是指定这两个属性不要混乱不同的渲染表面与显示维度(当然不是相对的像vw,vh,%,em,...)如果你不想要不可预测的结果;尽管一些SO用户一直在寻找解决方案。
As a result my advice (as a non-expert on HTML-canvas) would be to always specify those 2 attributes and not to mess with different rendering surface vs. display dimensions (certainly not relative ones like vw, vh, %, em, ...) if you don't want unpredictable results; although some SO users have been looking for a solution.
这篇关于为什么我在这个画布上创建的矩形不能放在正确的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!