[英]Drawing line to HTML5 canvas not working using javascript
我正在使用以下代碼在html畫布上畫一條線。 但不幸的是,我在畫布上看不到任何線條。 我什至沒有發現任何錯誤。
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<br> <br> <br>
<input id="start" type="button" value="Start" onclick="startstop()" />
<input type="button" value="Turn Left" />
<input type="button" value="Turn Right" />
<br> <br>
<canvas id="Canvas" style="width:800px; height: 600px; border: 1px solid black;"> </canvas>
<script>
function startstop(){
var elem = document.getElementById("start");
if (elem.value==="Start")
{
elem.value = "Stop";
var mycanvas=document.getElementById("Canvas");
// alert(mycanvas);
var ctx=mycanvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(10,400);
ctx.lineTo(200,400);
ctx.lineWidth=10;
ctx.strokeStyle="#ff0000";
ctx.stroke();
}
else
elem.value = "Start";
}
</script>
</body>
這是代碼的jsfiddle http://jsfiddle.net/8ebLLwa9/有人可以幫助我找到錯誤嗎?
您的畫布高度/寬度應該是畫布本身的屬性,而不是樣式屬性:
<canvas id='Canvas' width="800px" height="600px" style="border: 1px solid black;"></canvas>
另外,對於您的jsfiddle,將加載狀態從“ onLoad”更改為“ No wrap-in head”
使用css樣式的屬性width和height insetad定義畫布:
<canvas id='Canvas' width='800' height='600' style="border: 1px solid black;"> </canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.