2016-02-26 56 views
-2

我想要使用JavaScript來繪製一個簡單的應用程序,當我按下屏幕時(在觸摸屏上)繪製一個矩形。我不知道它爲什麼不起作用。下面是代碼:當屏幕被按下時,JavaScript繪製一個矩形

HTML

<canvas id="drawingboard" width="500" height="500" style="border:10px solid #000000;"> 
    You have a horrible browser that will not support an HTML canvas, so this won't work. 
</canvas> 

的JavaScript

var c = document.getElementById("drawingboard"); 
var ctx = c.getContext("2d"); 
var mouseDown = 0; 
document.body.ontouchstart = function() { 
    mouseDown+=1; 
} 
document.body.ontouchend = function() { 
    mouseDown-=1; 
} 
if (mouseDown == 1) { 

ctx.fillStyle = "#FF0000"; 
ctx.fillRect(0,0,150,75);} 
+0

您需要在事件處理程序中繪製。 –

回答

0

裘德,更換用下面的代碼填充行:

ctx.fillRect(event.clientX-50,event.clientY-50,100,100); 
0

我有完整的(但凌亂的)代碼:

<!DOCTYPE html> 
<html> 
<head> 
<title>Pixel Drawing</title> 
</head> 
<body> 
<canvas onclick=draw(event) 
id="drawingboard" width="850" height="390" 
style="border:10px    
          solid plum;"> 

You have a horrible browser that will not support an HTML 
canvas, so this won't work.</canvas> 
<script> 
var c = document.getElementById("drawingboard"); 
var ctx = c.getContext("2d"); 
var mouseDown = 0; 
document.body.ontouchstart = function() { 
mouseDown+=1; 
} 
document.body.ontouchend = function() { 
mouseDown-=1; 
} 
function draw(event){ 

ctx.color='gold'; 
ctx.fillStyle = "lime"; 
ctx.fillRect(event.clientX,event.clientY,100,100);} 
</script> 
</body> 
</html> 
+0

謝謝... ctx.color =「gold」;做?我知道填充樣式填充矩形,但金色似乎沒有做任何事情。 – Jude

+0

另外...當我點擊屏幕時,它會將矩形繪製到我點擊的位置的右​​側。 – Jude