HTML5文档 - Canvas Element未运行自定义'矩形的JavaScript参数。光标。请帮助:)
<head>
<title>Canvas Element & Custom Cursor</title>
</head>
<body id="body" style="background-color:red;">
<canvas id="canvas" width="600" height="400" style="background-
color:white;"> </canvas>
<script>
funtion CanvasProperties(){
var canvas = document.getElementById("canvas");
canvas = canvas.getContext("2d");
window.addEventListener("mousemove", CustomCursor, false);}
function CustomCursor(){
canvas.clearRect(0,0,600,400);
var xPosition = clientX;
var yPosition = clientY;
canvas.fillRect(xPosition, yPosition, 100, 100);}
window.addEventListener("load", CanvasProperties, false);
</script>
</body> </html>
答案 0 :(得分:1)
您根本没有使用event
对象 - clientX
而clientY
不是全局属性。
function CustomCursor(event){
canvas.clearRect(0,0,600,400);
var xPosition = event.clientX;
var yPosition = event.clientY;
canvas.fillRect(xPosition, yPosition, 100, 100);}
答案 1 :(得分:1)
这里有几个问题,有些问题已在Scimonster的回答中指出,但仍有一个重要问题。
要正确放置矩形,您需要“更正”鼠标位置。鼠标位置相对于客户端窗口,而相对于canvas元素则需要它们。
此外,您将使用上下文覆盖画布。为它使用单独的变量,并将它们放在全局(父)范围内。
这是一个完整版本(在脚本标签内):
var canvas, context; // place this in global scope
function CanvasProperties(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d"); // separate var for context...
window.addEventListener("mousemove", CustomCursor, false);
}
function CustomCursor(e){
var canvasRect = canvas.getBoundingClientRect(); // get position of canvas element
var xPosition = e.clientX - canvasRect.left; // adjust mouse positions to
var yPosition = e.clientY - canvasRect.top; // become relative to canvas
context.clearRect(0,0,600,400); // use context
context.fillRect(xPosition - 50, yPosition - 50, 100, 100);
}
window.addEventListener("load", CanvasProperties, false);
<canvas id="canvas" width=600 height=400></canvas>
答案 2 :(得分:0)
谢谢,伙计们!我们现在有一个自定义光标在画布上绘画:)
<!DOCTYPE html>
<html>
<head>
<title>Canvas Element & Custom Cursor</title>
</head>
<body id="body" style="background-color:red;">
<canvas id="canvas" width="600" height="400" style="background-
color:white;"> </canvas>
<script>
var canvas; var context;
function CanvasProperties(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
window.addEventListener("mousemove", CustomCursor, false);}
function CustomCursor(event){
var xPosition = event.clientX;
var yPosition = event.clientY;
context.fillRect(xPosition, yPosition, 100, 100);}
window.addEventListener("load", CanvasProperties, false);
</script>
</body>
</html>