[英]Canvas drawing errors (HTML5 and JavaScript)
I can usually research my problem and get an answer from someone else's mistake but this time i am having a rather unusual time finding an answer. 我通常可以研究我的问题并从其他人的错误中得到答案,但这次我有一个相当不寻常的时间找到答案。 The concept is that you can colorize
32x32
"pixels" on a 16x16
grid. 这个概念是你可以在
16x16
网格上着色32x32
“像素”。 My complete code follows: 我的完整代码如下:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jscolor.js"></script>
<title>Tiles</title>
</head>
<body>
<canvas id="canvas" height="512" width="512" onclick="draw(window.event)">
Oops, you don't have Canvases
</canvas>
<input type="text" value="000000" class="color"></input>
<script type="text/javascript">
var draw_a = document.getElementById("canvas").getContext("2d");
function draw(e) {
draw_a.fillStyle = "#" + document.getElementById("color").value;
draw_a.fillRect(
math.floor( e.clientX / 16 ),
math.floor( e.clientX / 16 ),
32,
32
);
}
draw_a.fillStyle = "#000000";
draw_a.fillRect( 0 , 0 , 512 , 512 );
</script>
</body>
</html>
You're dividing and rounding the click coordinates, but not multiplying the value back up again to map to canvas coordinates - there should also be 32 pixels between points, not 16. 您正在对点击坐标进行划分和舍入,但不会将值再次向上再次映射到画布坐标 - 点之间也应该有32个像素,而不是16个像素。
There's also no such function as math.floor
, it should be Math.floor
: 还没有
math.floor
这样的函数,它应该是Math.floor
:
var x = 32 * Math.floor(e.clientX / 32);
var y = 32 * Math.floor(e.clientY / 32);
draw_a.fillRect(x, y, 32, 32);
Lastly, your color input should have an id
of color
, not a class
最后,您的颜色输入应该具有
color
id
,而不是class
Working (in Chrome at least) demo at http://jsfiddle.net/alnitak/VJNdR/ 在http://jsfiddle.net/alnitak/VJNdR/工作(至少在Chrome中)演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.