每天一個JavaScript執行個體-canvas畫圖,javascript-canvas
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>每天一個JavaScript執行個體-canvas畫圖</title><style>.canvas{width:600px;height:500px;}</style><script>window.onload = function(){var imgcanvas = document.getElementById("imgcanvas");if(imgcanvas.getContext){var ctx = imgcanvas.getContext('2d');ctx.fillStyle="rgba(255,0,0,.1)";ctx.strokeStyle = "#000";//第一個ctx.fillRect(0,0,100,100);ctx.strokeRect(0,0,100,100);//第二個ctx.fillRect(50,50,100,200);//第三個ctx.strokeRect(80,130,200,100);}}</script></head><body><canvas class="canvas" id = "imgcanvas"><p>畫布</p></canvas></body></html>
html 5中,怎用javascript在canvas裡畫出一個笑臉?
利用基本路徑API
注意最後fill或stroke上去後之前緩衝的路徑資訊才會繪製到canvas上去
function drawShape(){
var canvas = document.getElementById('你的canvas的ID');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(75,75,50,0,Math.PI*2,true); // 外圓
ctx.moveTo(110,75);
ctx.arc(75,75,35,0,Math.PI,false); // 嘴
ctx.moveTo(65,65);
ctx.arc(60,65,5,0,Math.PI*2,true); //左眼
ctx.moveTo(95,65);
ctx.arc(90,65,5,0,Math.PI*2,true); // 右眼
ctx.stroke();
} else {
alert('你的瀏覽器不支援html5,請用chrome或Firefoxsafari .');
}
}
javascript在canvas中定義一個用來顯示的類,產生執行個體之後,怎來對其執行相應的滑鼠事件
這個只能給canvas添加事件,然後判斷點擊的時候的位置是否和矩形重疊