这是canvas元素的JavaScript。必须有一些东西用填充和绘制矩形的代码拧干:
function initCanvas() {
var ctx = document.getElementById("my_canvas").getContext("2d");
ctx.canvas.addEventListener("mousemove", function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var status = document.getElementById("status");
status.innerHTML = mouseX + " | " + mouseY;
});
ctx.canvas.addEventListener("click", function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
//alert(mouseX + " | " + mouseY);
ctx.fillStyle = "orange";
ctx.fillRect(mouseX, mouseY, 30, 30);
});
}
window.addEventListener("load", function(event) {
initCanvas();
});
这是带有canvas元素的HTML
<body>
<canvas id="my_canvas"></canvas>
<h2 id="status">0 | 0</h2>
</body>
这是CSS为画布提供高度和宽度
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100vh;
}
h2 {
color: black;
font-family: Varela Round;
}
答案 0 :(得分:1)
您需要设置画布大小。阅读更多HTML5 Canvas 100% height and width。
var canvas = document.getElementById("my_canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
但是你必须为实际的窗口大小实现resize事件。
window.addEventListener("resize", function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
工作示例:
var canvas = document.getElementById("my_canvas");
function initCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext("2d");
ctx.canvas.addEventListener("mousemove", function (event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
var status = document.getElementById("status");
status.innerHTML = mouseX + " | " + mouseY;
});
ctx.canvas.addEventListener("click", function (event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
//alert(mouseX + " | " + mouseY);
ctx.fillStyle = "orange";
ctx.fillRect(mouseX, mouseY, 30, 30);
});
}
window.addEventListener("load", function (event) {
initCanvas();
});
window.addEventListener("resize", function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%; /* set to % */
}
h2 {
color: black;
font-family: Varela Round;
}
<canvas id="my_canvas" width="1000" heigth="1000"></canvas>
<h2 id="status">0 | 0</h2>
答案 1 :(得分:0)
在CSS中设置画布的width
和height
并不足以告诉context
其尺寸。默认情况下,画布的width
为300,height
为150.当您调用ctx.fillRect
时,该坐标系统正在使用,以及它的原因是什么?一切都伸了出来。
您需要的是使用JavaScript设置画布大小。尝试向resize
添加window
侦听器,并使用JavaScript设置画布的width
和height
。
window.addEventListener('resize', resizeCanvas);
// call it initially because 'resize' events won't trigger on page load
resizeCanvas();
function resizeCanvas() {
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
这将更新上下文维度,并且您实际上是根据窗口坐标进行绘制的。