绘制响应画布,是100%的宽度和高度
drawing to responsive canvas that is 100% width and height
我试图在大画布上获得跟随鼠标光标的形状。这段代码没有按预期工作。如果画布是屏幕的100%宽度/高度,我如何修改这个相对画布大小?
同样,我知道requestanimationframe,但为了演示这个问题,请忽略它(我正在使用它,但它是一个与本示例无关的复杂的计时混乱)。
小提琴:https://jsfiddle.net/gs5a4z84/
CSS:* { margin: 0; padding: 0;}
body, html { height:100%; }
canvas {
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: pixelated; /* Chrome */
position:absolute;
width:100%;
height:100%;
}
HTML/JS: <!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet"</link>
</head>
<body>
<div id="wrapper">
<canvas id="ctx" width="256" height="144"></canvas>
</div>
<script>
var mouseX, mouseY;
const WIDTH = 256;
const HEIGHT = 144;
var ctx = document.getElementById('ctx').getContext('2d');
ctx.canvas.addEventListener('mousemove', setMousePosition, false);
function setMousePosition(e) {
mouseX = e.clientX;
mouseY = e.clientY;
}
function drawCursor() {
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.fillStyle = "#FF6A6A";
ctx.fillRect(mouseX, mouseY, 16, 16);
}
setInterval(function (){
drawCursor();
}, 40);
</script>
</body>
</html>
谢谢你的帮助。
如果你为画布对象使用CSS宽度和高度属性,那么你实际上不会改变画布上有多少像素,而是改变它的大小。要解决这个问题,使用JavaScript设置画布的宽度和高度属性:
JavaScript:ctx.canvas.width = innerWidth;
ctx.canvas.height = innerHeight;
CSS: body, canvas {
margin: 0;
padding: 0;
}
相关文章:
- iframe上的100%自动高度
- ExtJS使网格高度达到100%
- 使页面高度为浏览器的100%
- 如何将 dojox.mobile.View 设置为 100% 的高度
- 3 行布局,100% 高度:1 自动,1 自动滚动,1 固定
- 相对位置和高度100%
- iframe高度100%不起作用
- 高度:100%在ng重复内
- 按下按钮使$(“身体”).css(“高度”:“100%”)
- 高度 100% 自定义滚动条
- 为什么我的代码适用于高度:100px,而不是高度:100%
- 安卓平板电脑-Chrome浏览器/本地浏览器:地址栏和固定高度(100%)问题
- scrollTop Broken:车身高度100%,溢出自动
- HTML/CSS高度100%和像素
- 高度100%在几个级别
- 高度100%的属性不能在css的bootstrap 3中使用
- 高度100%的html元素safari iOS
- if语句体高度<100% javascript / jquery
- Iframe的高度100%的容器在iphone.这是不可能的吗?
- Iframe自动高度100%,跨域